我需要重载 =
才能对我的类的实例进行深度复制。
它工作得很好,直到我尝试将一些随机数据设置为输入。然后我收到这条消息:
Exception: STATUS_ACCESS_VIOLATION at eip=004042F3 and then it prints out the stack..
我假设,我需要在复制之前删除数组中的值,但我无法弄清楚它应该是什么样子。 我试过这个:
for (int i = 0; i != position-1; i++) {
for (int j=0;j!=db[i]->position-1;j++)
delete &db[i]->change[j];
delete db[i];
}
delete[] db;
db = new DbPerson*[other.size];
,但情况变得更糟,程序甚至更早以失败告终。
这里是使用组件的声明:
int size;
int position;
DbPerson** db;
...
class DbChange {
public:
DbChange();
const char* date;
const char* street;
const char* city;
};
DbChange::DbChange() {
date = "";
street = "";
city = "";
}
class DbPerson {
public:
DbPerson(void);
const char* id;
const char* name;
const char* surname;
DbChange * change;
int position;
int size;
};
DbPerson::DbPerson() {
position = 0;
size = 1;
change = new DbChange[1];
}
所有数组都可以调整大小,当没有足够的空间时,保存在其中的项目的实际计数保存在 position
变量中。请不要建议我使用 Vector
或 string
,因为我不允许使用它们。我敢肯定,重载 =
的函数成功结束,并且在它尝试完成分配时会打印出此错误消息。
如果有人可以告诉我,析构函数应该是什么样子,我会很高兴,因为我已经尝试解决这个问题几个小时但没有成功:(
最佳答案
您不需要在 DbPerson 的每个对象中预删除 DbChange。您可以在 DbPerson 中调用 DbChange 的析构函数。
看看:
class DbChange
{
public:
const char* id;
const char* Name;
DbChange(): id(""), Name("")
{}
~DbChange()
{
delete [] id;
delete [] Name;
}
};
class DbPerson
{
public:
const char* id;
const char* name;
const char* surname;
DbChange * change;
int position;
int size;
DbPerson(): id(""), name(""), surname(""), position(0), size(1)
{
change = new DbChange[1];
}
void SHOW(void) const
{
cout << "Name: " << name << endl
<< "Surname: " << surname << endl
<< "position: " << position << endl;
}
~DbPerson()
{
delete [] change; // Calling Destructor for DbChange
delete [] id;
delete [] name;
delete [] surname;
}
};
int main()
{
const int global_size_of_DbPerson = 10;
DbPerson** db;
db = new DbPerson* [global_size_of_DbPerson];
for(int i = 0; i < global_size_of_DbPerson; i++)
{
db[i] = new DbPerson [global_size_of_DbPerson];
}
for(int i = 0; i < global_size_of_DbPerson; i++)
{
delete [] db[i];
}
cout << "It Worked\n";
delete [] db;
return 0;
}
关于c++ - 重载中的析构函数出现问题 = STATUS_ACCESS_VIOLATION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15995004/