gpt4 book ai didi

c++ - 类具有带有动态数组成员的类

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:45 24 4
gpt4 key购买 nike

我有一个带有动态数组 (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。我这样做的方式是,内存分配给 temp,然后 myDA 指向 temp。但我想分配给 temp 的内存在构造函数完成后会被删除。因此,当我执行程序时出现内存错误。那么如何正确分配内存呢?

最佳答案

使用构造函数初始化列表:

App(int N) : myDA(N) {}

请注意您的 DA除非您遵循rule of three,否则类(class)会被破坏,或使用 std::vector<double> 简化问题, 一个 std::unique_ptr<double[]>boost scoped array :

#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.
};

关于c++ - 类具有带有动态数组成员的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19118098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com