我有一个带有动态数组(DA)的类
class DA{
private:
double* array;
int size N;
//other stuff
public:
DA(){
array=NULL;
}
DA(int PN){
N=PN;
array=new double[N];
};
//destructor and other stuff
}
这似乎还可以。现在,我想要一个具有一个DA对象的“应用程序”类:
class App{
private:
DA myDA;
public:
App(int N){
//create myDA with array of size N
DA temp(N);
myDA=temp;
};
}
问题是,我不知道如何在App构造函数中创建myDA。我这样做的方式是为临时内存分配内存,然后myDA指向临时内存。但是我猜为temp分配的内存在构造函数完成后会被删除。因此,执行程序时出现内存错误。那么如何正确分配内存呢?
使用构造函数初始化列表:
App(int N) : myDA(N) {}
请注意,DA
除非遵循三法则,否则类将被破坏,或者使用std::vector<double>
,std::unique_ptr<double[]>
或boost范围化数组简化问题:
#include <vector>
class DA{
private:
std::vector<double> data; // "array" is a std lib container name
public:
DA(int PN) : data(PN) {}
// no need to write destructor, copy constructor or assignment operator.
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句