有一个用于使受保护的析构函数虚拟

有一个用于使受保护的析构函数虚拟

本文介绍了有一个用于使受保护的析构函数虚拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/*Child is inherited from Parent*/
class Parent {
  public:
    Parent () //Constructor
    {
        cout << "\n Parent constructor called\n" << endl;
    }
  protected:
    ~Parent() //Dtor
    {
        cout << "\n Parent destructor called\n" << endl;
    }
};

class Child : public Parent
{
  public:
    Child () //Ctor
    {
        cout << "\nChild constructor called\n" << endl;
    }
    ~Child() //dtor
    {
        cout << "\nChild destructor called\n" << endl;
    }
};

int main ()
{
    Parent * p2 = new Child;
    delete p2;
    return 0;
}

如果我使 Parent

推荐答案

只是为了解决这个问题,给一个例子:假设你有一个基类实现引用计数。你有一个 addRef 和一个 release 方法,你希望你的对象被销毁,如果(和 if)内部计数器通过调用 release 达到零。

Just to give one example: Say you have an base class which implements reference counting. You have an addRef and a release method and you want your object to be destroyed, if (and only if) the internal counter reaches zero through a call to release.

所以,首先你想要你的析构函数保护(因为你只想从 relase 中销毁对象)。

So, first you want your destructor protected (since you only want to destroy the object from within relase).

如果你计划从你的类派生,你也想要你的析构函数是虚拟的,因为你需要一个虚拟析构函数,每当你想通过指针来销毁一个子对象到基类(感谢@sharptooth的提示...)

If you plan to derive from your class, you also want to have your destructor virtual, since you need a virtual destructor whenever you want to destroy a child object through a pointer to a base class (thanks @sharptooth for the hint ...)

这篇关于有一个用于使受保护的析构函数虚拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:40