当压倒一切的一类C++(与一个虚拟析构)我实现析构再次作为虚拟的继承类,但这样做,我需要电话的基析构?

如果是这样我想象它这样的事情...

MyChildClass::~MyChildClass() // virtual in header
{
    // Call to base destructor...
    this->MyBaseClass::~MyBaseClass();

    // Some destructing specific to MyChildClass
}

我说的对吗?

有帮助吗?

解决方案

没有,析构函数被自动构造的相反的顺序调用。 (最后一个基类)。不调用基类析构函数。

其他提示

不,你不需要叫基析构、基析构是总是叫你由得出析构函数。 请参阅我的有关答案在这里为了破坏.

要了解为什么你想要一个虚拟析构基类中,请见的代码如下:

class B
{
public:
    virtual ~B()
    {
        cout<<"B destructor"<<endl;
    }
};


class D : public B
{
public:
    virtual ~D()
    {
        cout<<"D destructor"<<endl;
    }
};

当你这样做:

B *pD = new D();
delete pD;

然后如果你没有一个虚拟析构在B,只有-B()将称为。但因为你有一个虚拟析构,第一-D()将呼吁,然后-B().

什么别人说,但也请注意,您不必声明析构函数在派生类中的虚拟。一旦你声明析构函数虚拟的,因为你在基类中做,所有派生的析构函数将是虚拟的你是否宣布他们这么与否。换句话说:

struct A {
   virtual ~A() {}
};

struct B : public A {
   virtual ~B() {}   // this is virtual
};

struct C : public A {
   ~C() {}          // this is virtual too
};

没有。不像其他的虚拟方法,其中,你会显式调用从衍生为“链”的调用基方法,编译器生成的代码来调用析构函数,在其中它们的构造被称为相反的顺序。

没有,你永远不会调用基类的析构函数,它总是自动调用像其他人指出,但这里是有效果的概念证明:

class base {
public:
    base()  { cout << __FUNCTION__ << endl; }
    ~base() { cout << __FUNCTION__ << endl; }
};

class derived : public base {
public:
    derived() { cout << __FUNCTION__ << endl; }
    ~derived() { cout << __FUNCTION__ << endl; } // adding call to base::~base() here results in double call to base destructor
};


int main()
{
    cout << "case 1, declared as local variable on stack" << endl << endl;
    {
        derived d1;
    }

    cout << endl << endl;

    cout << "case 2, created using new, assigned to derive class" << endl << endl;
    derived * d2 = new derived;
    delete d2;

    cout << endl << endl;

    cout << "case 3, created with new, assigned to base class" << endl << endl;
    base * d3 = new derived;
    delete d3;

    cout << endl;

    return 0;
}

的输出是:

case 1, declared as local variable on stack

base::base
derived::derived
derived::~derived
base::~base


case 2, created using new, assigned to derive class

base::base
derived::derived
derived::~derived
base::~base


case 3, created with new, assigned to base class

base::base
derived::derived
base::~base

Press any key to continue . . .

如果您的碱基类的析构作为虚拟哪一个应,然后壳体3点的结果将是相同的情况下,1和2。

没有。它的自动调用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top