c++ - 派生类的析构函数发生了什么?

标签 c++ visual-c++

<分区>

这是我试图理解其输出的代码。

class A
    {
    public:

        A();
        ~A(){ cout<<"Destructor Called from A"<<endl;}
        A(int x):Z(x){ cout<<"Constructor Called from A"<<endl; };

    private:
        int Z;
    };

    class B:public A
    {
    public:

        B();
        ~B(){ cout<<"Destructor Called from B"<<endl;}
        B(int x):A(x),Y(x){ cout<<"Constructor Called from B"<<endl; };

    private:
        int Y;
    };

    int main() {

        A *a = new B(10);        
        delete a;

        return 0;
    }

我得到的输出是

Constructor Called from A
Constructor Called from B
Destructor Called from A

我的问题是,B 类的析构函数发生了什么? 对象切片在这里发挥作用吗?

最佳答案

您需要使父类(super class)的析构函数成为虚拟的:

 class A {
    virtual ~A(){ cout<<"Destructor Called from A"<<endl;}

关于c++ - 派生类的析构函数发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26594254/

相关文章:

c++ - MFC 扩展 CFileDialog

c++ - 重载运算符 = 错误

c++ - 如何按值返回 "auto"返回类型函数

c++、msxml 和智能指针

c++ - 为什么我可以在没有调用 CoInitializeEx 的情况下调用 StringFromCLSID?

c++ - << 的运算符重载需要 const;产生头痛

c++ - 如何使用可变模板参数保存可变数量的参数?

c++ - 找到与另一个二进制模式匹配的所有 2 位值,然后将它们相加

c++ - 在 C++ 中创建另一个类中的类的对象

c++ - 检测图像中的填充矩形