gpt4 book ai didi

c++ - 具有非虚拟析构函数的派生类

转载 作者:IT老高 更新时间:2023-10-28 13:57:52 26 4
gpt4 key购买 nike

在任何情况下派生类具有非virtual 析构函数是合法的吗?非virtual 析构函数表示不应将类用作基类。派生类的非virtual析构函数会像Java final修饰符的弱形式吗?

我对派生类的基类有virtual析构函数的情况特别感兴趣。

最佳答案

Are there any circumstances in which it is legitimate for a derived class to have a non-virtual destructor?

是的。

A non-virtual destructor signifies that a class should not be used as a base-class.

不是真的;非虚拟析构函数表示通过 base 指针删除 derived 的实例将不起作用。例如:

class Base {};
class Derived : public Base {};

Base* b = new Derived;
delete b; // Does not call Derived's destructor!

如果不按上述方式进行delete,那就可以了。但如果是这种情况,那么您可能会使用组合而不是继承。

Will having a non-virtual destructor of a derived class act like a weak form of the Java final modifier?

不,因为 virtual-ness 会传播到派生类。

class Base
{
public:
virtual ~Base() {}
virtual void Foo() {};
};

class Derived : public Base
{
public:
~Derived() {} // Will also be virtual
void Foo() {}; // Will also be virtual
};

在 C++03 或更早版本中没有内置的语言机制来防止子类 (*)。反正这不是什么大问题,因为你应该总是 prefer composition over inheritance .也就是说,当“is-a”关系比真正的“has-a”关系更有意义时,使用继承。

(*) 'final' 修饰符是在 C++11 中引入的

关于c++ - 具有非虚拟析构函数的派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7403883/

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