The program I should create will use a dynamic array which will store Revenue objects. The array should be dynamic so that the user of the program can enter the number of Revenue records. I am confused as to how to pull this off.
由于
例如,说我有一个:class Revenue
{
private:
(tons of function members in middle)
public:
}
现在我需要创建一个看起来像这样的数组
int arry;
cout << "how many Revenue tiers do you want?: "; cin >> arry;
Revenue rev[arry];//dynamic array
(这当然是错误的)
答案 0 :(得分:3)
你必须为它动态分配内存:
Revenue* rev = new Revenue[arry];
当你完成它时,不要忘记删除它
delete[] rev;
虽然使用智能指针(例如std::unique_ptr
(或std::shared_ptr
)要好得多,但对于数组std::shared_ptr
使用起来有点棘手,因为您必须定义自己的解除分配器
使用std::unique_ptr
,您可以编写代码,如
std::unique_ptr<Revenue[]> p(new Revenue[arry]);
并且忘记了破坏,删除等。当智能指针超出范围时,它会处理所有清理工作。
答案 1 :(得分:2)
您不必手动使用动态分配/取消分配 ,而是
std::vector < Revenue > vec;
cin >> arry;
vec.resize( arry ); // Resizes vec to hold exactly arry no. of objects