gpt4 book ai didi

c++ - 不需要基类析构函数的定义?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:21 26 4
gpt4 key购买 nike

在我看到的所有关于多态性的示例中,基类的析构函数都是 virtual 并且它是用空主体定义的。

我正在努力解决这个问题:为什么它必须是一个空的 body ?如果该方法只是声明为 virtual 而不是用空主体定义,为什么它不起作用?那岂不是默认的析构函数就实现了?或者它被声明为 virtual 的事实甚至会抑制默认定义并强制显式定义主体?

这就是我的意思:

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

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

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

另外,为什么在抽象类中必须这样定义(空主体)?我曾尝试声明像这样的抽象类的析构函数 virtual ~A() = 0,但编译器不允许我这样做。

最佳答案

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

因为无法调用未定义的函数。就那么简单。如果您不声明 析构函数,编译器将隐式定义 一个。但是,如果您自己提供了一个声明,那么编译器将不再提供一个定义。不过,您可以在 C++11 中明确为其指定默认定义。

virtual ~A() = default;

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.

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

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

关于c++ - 不需要基类析构函数的定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24231105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com