作为学校作业的一部分,我们必须创建一个抽象类并使用一个寄存器类来包含它们。抽象类有两个下类。 喜欢动物>狗/猫赋值操作符创建指针并且不会使删除成为可能
在这个任务中,我们必须做一个赋值操作符,但是在使用我所做的那个之后,程序出了问题。
我制作了两个寄存器
r1; r2;
然后使用运营商
r2 = r1;
,并在程序退出时,它进入R1的destruktor,删除它,到达R2,并得到“访问冲突读取位置”
我猜这是因为运营商创建了一个从指针r2到r1,所以当r1被删除时。
运营商:
Register& Register::operator=(Registerconst &other)
{
for (int i = 0; i < this->count; i++)
{
delete this->animals[i];
}
delete[] this->animals;
this->name = other.name;
this->size = other.size;
this->count = other.count;
this->animals= new Animal*[this->size];
for (int i = 0; i < this->count; i++)
{
animals[i] = other.animals[i];
}
for (int i = count; i < this->size; i++)
{
this->animals[i] = nullptr;
}
return *this;
}
的析构函数不是虚拟的。不知道这是导致它
由于要求在此处,它被用来
AnimalRegister r1("Name 1");
AnimalRegister r2("Name 2");
// some stuff being added to r1
r2 = r1;
return 0;
构造的地方:
AnimalRegister::AnimalRegister(string name)
{
this->name = name;
this->size = 10;
this->count = 0;
this->animals = new Animal*[this->size];
for (int i = 0; i < this->size; i++)
animals[i] = nullptr;
}
析构函数:
AnimalRegister::~AnimalRegister()
{
for (int i = 0; i < this->count; i++)
delete animals[i];
delete[] animals;
}
难道这只是我不知道的OOP术语吗?什么是“注册课程”? –
你想要什么被称为[共享指针](http://en.cppreference.com/w/cpp/memory/shared_ptr)。你可以阅读_implementation detail_部分找到想法,如果你想自己创建。 – Lol4t0
@CodyGray可能只是翻译问题,如果指定原本不是英文的 – Lol4t0