0

我需要重载=才能对我的类的实例进行深度复制。在我尝试将大量随机数据设置为输入之前,它工作得很好。然后我收到这条消息:

例外: STATUS_ACCESS_VIOLATION at eip=004042F3 然后它打印出堆栈..

我假设,我需要在复制之前删除数组中的值,但是我不知道它应该是什么样子。我试过这个:

  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变量中。请不要建议我使用Vectoror string,因为我不允许使用它们。我敢肯定,=成功重载的函数会结束,并且在尝试完成分配时会打印出此错误消息。

如果有人可以告诉我,析构函数应该是什么样子,我会很高兴,因为我已经尝试解决这个问题几个小时但没有任何成功:(

4

1 回答 1

2

您不需要在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;
}
于 2013-04-14T05:07:59.390 回答