基类析构器的定义不需要? [英] Definition of base class destructor not needed?

查看:119
本文介绍了基类析构器的定义不需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在所有的例子中,我已经看到了多态性的基类的析构函数是 virtual ,它被定义为一个空体。

In all the examples I have seen about polymorphism the destructor of the base class is virtual and it is defined with an empty body.

我试图让我的头:这是为什么它必须是一个空身体?为什么不工作,如果方法只是声明为 virtual 但没有用emtpy身体定义?它不会实现然后由默认析构函数?或者,它被声明为 virtual 的事实,甚至默认定义,并强制显式定义的身体?

I am trying to get my head around this: why does it have to be an empty body? Why doesn't it work if the method is just declared as virtual but not defined with an emtpy body? Wouldn't it be implemented then by the default destructor? Or the fact that it's being declared as virtual supresses even the default definition and forces to explicitly define the body?

这是我的意思:

class A {
public:
    virtual void f();
    virtual ~A() {}
}

class B : public A {
public:
    ~B() {
        // destroy whatever
    }
}

为什么不能〜A()被声明为这样 virtual〜A(); 没有定义?

Why can't ~A() be declared just like this virtual ~A(); without definition?

此外,为什么它必须像抽象类中那样定义(使用空体)?我试图声明一个抽象类的destuctor像这样 virtual〜A()= 0 ,编译器不让我这样做。

Also, why does it have to be defined like that (with the empty body) in abstract classes? I have tried to declare the destuctor of an abstract class like this virtual ~A() = 0 and the compiler didn't let me do that.

推荐答案


为什么不能〜A()像这样 virtual〜A(); 没有定义?

那就是没有定义就不能被调用。就那么简单。如果您不声明了析构函数,编译器会隐式地定义一个。但如果您自己提供声明,则编译器不再提供定义。你可以显式地给它在C ++ 11中的默认定义。

Because a function that isn't defined can't be called. Simple as that. If you don't declare the destructor, the compiler implicitly defines one. But if you provide a declaration yourself then the compiler no longer provides a definition. You can explicitly give it the default definition in C++11 though.

virtual ~A() = default;




此外,为什么必须这样定义空体)在抽象类?我试图声明一个抽象类的destuctor像这样 virtual〜A()= 0 ,编译器不让我这样做。

Also, why does it have to be defined like that (with the empty body) in abstract classes? I have tried to declare the destuctor of an abstract class like this virtual ~A() = 0 and the compiler didn't let me do that.

同理。只要一个析构函数被调用,它需要有一个定义,就像任何其他函数。通常,纯虚函数从不被调用,但析构函数是异常。您必须提供一个定义。

Same reason. As long as a destructor is called, it needs to have a definition, just like any other function. Normally a pure virtual function is never called, but destructors are an exception. You will have to provide a definition.

class A {
// ...
    virtual ~A() = 0; // declare destructor as pure virtual
};
// ...
A::~A() {} // define destructor

这篇关于基类析构器的定义不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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