이것이 좋은 코딩 방법인지 확실하지 않으므로 잘못 되었다면 수정하십시오.역 참조 포인터의 배열을 삭제해야합니까?
동적으로 Transaction 클래스를 만들고이 객체를 Transaction 객체의 벡터에 추가하는 방법이 필요했습니다. 이것은 내가 한 것입니다 :
class Transaction {
int data;
Transaction(int d) : data(d) {}
};
class Container {
std::vector<Transaction> transactions;
void createTransaction();
};
void Container::createTransaction() {
int data;
std::cout << "Enter your data: ";
std::cin >> data;
Transaction t = new Transaction(data);
// In order to keep the object from destruction at end of function.
// Possibly could be done with static as well.
transactions.push_back(*t);
}
벡터는 포인터가 아닌 객체의 벡터입니다. 이것은 동적 메모리를 삭제할 필요가없는 경우인가요? 프로그램/스코프가 끝나면 자동으로 삭제됩니다.
개체를 동적으로 만들고 저장하는 것은 어려운 방법입니까?
이 구현은 바람직하지 않을 수 있습니다. 나는't' *를 동적으로 할당 할 이유가 없다고 생각합니다. 입력 후에'transactions.emplace_back (data);'을 수행하고 나머지는 던져 버린다. – WhozCraig