gpt4 book ai didi

c++ - 为什么这个虚拟析构函数在 C++ 中不起作用?

转载 作者:行者123 更新时间:2023-11-30 05:03:18 25 4
gpt4 key购买 nike

<分区>

我正在尝试删除子类的对象。虽然我使用了虚拟析构函数,但我仍然收到错误消息:

malloc: *** error for object 0x7ffee08bab50: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

我的代码是:

#include <iostream>

using namespace std;

class Animal{
protected:
int age;
public:
Animal(){
age = 0;
cout << "ctor Animal" << endl;
}
virtual ~Animal(){
cout << "dtor Animal" << endl;
}
};

class Mammal : public Animal{
public:
Mammal(){
age = 0;
cout << "ctor Mammal" << endl;
}
~Mammal(){
cout << "dtor Mammal" << endl;
}
};

int main(){
Mammal *dog = new Mammal();
delete &dog;
}

如果有人帮助我,我将不胜感激!

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com