我是新手,我知道这是一个非常基本的概念,也可能是重复的。 一旦调用构造函数,就必须调用其对应的析构函数,这不是真的吗? [在 Dev C++ 上运行的代码]
class Base
{
public:
Base() { cout<<"Base Constructor\n";}
int b;
~Base() {cout << "Base Destructor\n"; }
};
class Derived:public Base
{
public:
Derived() { cout<<"Derived Constructor\n";}
int a;
~Derived() { cout<< "Derived Destructor\n"; }
};
int main () {
Base* b = new Derived;
//Derived *b = new Derived;
delete b;
getch();
return 0;
}
给出输出
Base Constructor
Derived Constructor
Base Destructor
最佳答案
您的代码有未定义的行为。基类的析构函数必须是 virtual
才能使以下具有定义的行为。
Base* b = new Derived;
delete b;
来自 C++ 标准:
5.3.5 Delete
3 In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
所以在你的例子中,静态类型是Base
,动态类型是Derived
。所以 Base
的析构函数应该是:
virtual ~Base() {cout << "Base Destructor\n"; }
关于c++ - 在 C++ 继承中,当指向基类的指针对象指向派生类时,不调用派生类析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49928668/