简体   繁体   English

抽象类、继承和虚拟析构函数

[英]Abstract classes, inheritance and virtual destructors

Even though B 's destructor isn't virtual , I still can call C 's destructor through B pointer.即使B的析构函数不是virtual ,我仍然可以通过B指针调用C的析构函数。

Does this mean that only the only outermost abstract class needs to have a virtual destructor?这是否意味着只有最外层的抽象类需要有一个virtual析构函数?

And if so, why does it work like this?如果是这样,为什么它会这样工作?

Is it becase B is inheriting A 's destructor?是因为B继承了A的析构函数吗?

#include <iostream>

struct A {
    virtual ~A() {
        std::cout << "~A\n";
    }

    virtual void
    function_a() = 0;
};

struct B : A {
    /*
    virtual ~B() {
        std::cout << "~B\n";
    }
    */

    virtual void
    function_b() = 0;
};

struct C : B {
    ~C() override {
        std::cout << "~C\n";
    }

    void
    function_a() override {
        std::cout << "function_a\n";
    }

    void
    function_b() override {
        std::cout << "function_b\n";
    }
};

int
main() {
    B * b = new C();

    b->function_a();
    b->function_b();

    delete b;
}

The destructor of B and C are both virtual too. BC的析构函数也是virtual Destructors won't be inherited, but if the base class' destructor is virtual , the derived destructor overrides it and is also virtual ;析构函数不会被继承,但如果基类的析构函数是virtual ,则派生的析构函数会覆盖它并且也是virtual despite of virtual is specified explicitly or not.尽管显式指定了virtual

Even though destructors are not inherited, if a base class declares its destructor virtual , the derived destructor always overrides it.即使析构函数没有被继承,如果基类声明它的析构函数virtual ,派生的析构函数总是覆盖它。

and

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).那么这个 Derived 类中的函数也是virtual (无论其声明中是否使用关键字virtual )并覆盖Base::vf (无论其声明中是否使用单词override )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM