这只是一个了解继承如何工作的测试项目。Cat 是 Mammal 的子类,而 Mammal 又是 Animal 的子类。
int main()
{
Cat* cat1 = new Cat("nosy grey", 1.0d, 3);
Cat* cat2 = new Cat("purply green", 2.0d, 4);
Cat* cats[] = {cat1, cat2};
delete [] cats;
}
所以我真的不能那样做,因为那样我就明白了。
*** Error in `/home/max/git/info-2-ss/Blatt3/Aufgabe2/main.exe': double free or corruption (out): 0x00007fff55fd7b10 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x80a46)[0x7f3a07452a46]
/home/max/git/info-2-ss/Blatt3/Aufgabe2/main.exe[0x40178e]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7f3a073f3ea5]
/home/max/git/info-2-ss/Blatt3/Aufgabe2/main.exe[0x400d39]
当我的构造函数和析构函数被调用时,我会输出,所以当我的 Cats 被创建时,我会得到这样的结果:
Called ctor of Animal with age: 3
Called ctor of Mammal with hairLength: 1
Called ctor of Cat with eyecolor: nosy grey
当我稍微更改我的代码时,它显示为:
delete [] *cats;
那么我会期望每只猫都会像这样调用我的 dtors:
Called dtor of Cat
Called dtor of Mammal
Called dtor of Animal
相反,我得到了这一行:
Called dtor of Cat
摘要:如何有效地删除我的数组,以便调用我的所有 dtor?