我有以下代码: 在Client.cpp中,有一个构造函数正在为数组进行内存分配" conturi"类型为ContBancar。
Client::Client(string nume, string prenume, string adresa)
{
this->nume = nume;
this->prenume = prenume;
this->adresa = adresa;
nrCont = 0;
ContBancar** conturi = new ContBancar*[50];
}
然后有一种方法是在" conturi"中添加一个帐户。阵列:
void Client::adaugaCont(ContBancar* contNou)
{
conturi[nrCont++] = contNou;
}
这是我在Main.cpp中的代码:
ContBancar ron1 ("1.r", 0, Banca::RON);
Client ioana ("Pop", "Ioana", "Str Dorobantilor 3/4");
ioana.adaugaCont(&ron1);
但它在运行时给了我访问冲突错误,比如数组' conturi'没有分配内存。我不明白为什么,因为内存应该在构造函数中分配。
有人可以帮我吗?
答案 0 :(得分:4)
Client::Client(string nume, string prenume, string adresa)
{
this->nume = nume;
this->prenume = prenume;
this->adresa = adresa;
nrCont = 0;
//here is your problem!
ContBancar** conturi = new ContBancar*[50];
}
您将conturi重新定义为一个新数组,其指针存储在构造函数的本地范围内。
将行更改为:
conturi = new ContBancar*[50];
然后您将使对象的conturi指针指向已分配的内存 这也将解决您引入的内存泄漏问题 (指向堆的指针超出范围。堆上的内存泄漏)
甚至更好,使用std :: vector 在类定义中:
std::vector<ContBancar> conturi;
您无需使用new
和delete
自行管理内存,也不限于固定数量的元素。
答案 1 :(得分:3)
您正在使用以下行声明一个新的指针变量:
ContBancar** conturi = new ContBancar*[50];
并且指针变量将在函数调用结束时被破坏并且内存泄漏保持任何其他同名成员变量不变。
您应该使用成员变量conturi
(假设您有其余代码中的一个):
Client::Client(string nume, string prenume, string adresa)
{
this->nume = nume;
this->prenume = prenume;
this->adresa = adresa;
nrCont = 0;
conturi = new ContBancar*[50];
}
或者你可以使用一个std::vector<ContBancar> conturi
成员变量,它可能更容易使用和处理。
这是一个简单的复制器,可以更好地理解问题:
class Client {
public:
int** conturi = 0;
void function() {
int** conturi = new int*[50];
}
};
int main()
{
Client obj;
obj.function();
if(obj.conturi == 0)
std::cout << "this is still zero"; // This will get printed
}