通过删除基类来破坏派生类 [英] Destructing derived class by deleting base class

查看:88
本文介绍了通过删除基类来破坏派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况类似于以下代码:

I have a situation that looks like the following code:

#include <iostream>

class A
{
public:
    A() { std::cout << "A created!" << std::endl; }
    ~A() { std::cout << "A destroyed!" << std::endl; }

    virtual const char* Name() { return "A"; }
};

class B : public A
{
public:
    B() { std::cout << "B created!" << std::endl; }
    ~B() { std::cout << "B destroyed!" << std::endl; }

    const char* Name() { return "B"; }
};

int main()
{
    A* a = new B();

    std::cout << a->Name() << "\n";

    delete a;

    return 0;
}

我也希望B也被摧毁.是否可以在其析构函数中实现此功能,或者我是否必须实现虚拟的Destroy()方法或类似的方法?

I want B to be destroyed when A is destroyed too. Is this possible in its destructor or do I have to implement a virtual Destroy() method or something like that?

推荐答案

根据经验,如果您的任何方法都是虚拟的,则析构函数也必须是虚拟的.如果不是,则声明的变量类型决定要调用哪个析构函数,而这几乎永远不是您想要的.在所有情况下,您都需要99.9%的运行时类型作为析构函数.

As a rule of thumb, if any of your methods are virtual, the destructor must also be virtual. If it isn't, the declared type of a variable decides which destructor gets called, which is almost never what you want. 99.9% of all cases, you want the destructor from the runtime type.

这篇关于通过删除基类来破坏派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆