c++ - 在 C++ 继承中,当指向基类的指针对象指向派生类时,不调用派生类析构函数

标签 c++ inheritance

我是新手,我知道这是一个非常基本的概念,也可能是重复的。 一旦调用构造函数,就必须调用其对应的析构函数,这不是真的吗? [在 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/

相关文章:

inheritance - UML:专业类之间的关联

C++。 1类具有变化的参数

c++ - 模板模板参数参数名称用法

c++ - 如何在移动设备上启动短代码?

java - 在静态父方法中访问子类常量

inheritance - 继承类型时获取 "value is not defined"

c++ - 为什么该区域返回为 0?

c++ - 具有可变模板参数的函数指针

java - 转换类以调用子类中的方法

java - 使用继承定义 nxn 矩阵