具有非虚拟析构函数的派生类 [英] Derived class with non-virtual destructor
问题描述
在任何情况下,派生类有一个非 - virtual
析构函数是合法的吗?非 - virtual
析构函数意味着一个类不应该被用作基类。将一个派生类的非 - 虚拟
析构函数像一个弱的形式的Java final
修饰符? p>
编辑:我特别感兴趣的是派生类的基类有 virtual
destructor。
在任何情况下, b $ b类有非虚拟析构函数?
是的。
< blockquote>
一个非虚拟析构函数表示一个类不应该用作
a基类。
不是真的;非虚拟析构函数表示通过 base
指针删除派生的
实例将不起作用。例如:
class Base {};
class Derived:public Base {};
Base * b = new Derived;
delete b; //不调用Derived的析构函数!
如果您不执行 delete
上面的方式,那么会很好。但是如果是这样,那么你可能会使用组合而不是继承。
将具有派生类的非虚拟析构函数像$ a
弱形式的Java最终修改器?
否,因为 virtual
- 传播到派生类。
class Base
{
public:
virtual〜Base(){}
virtual void Foo(){};
};
class Derived:public Base
{
public:
〜Derived(){} //也将是虚拟
void Foo ; // Will also be virtual
};
C ++中没有内置的语言机制来防止子类。这不是很重要的问题,因为你应该总是偏好组合继承。也就是说,当is-a关系比真正的has-a关系更有意义时,使用继承。
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. Will having a non-virtual
destructor of a derived class act like a weak form of the Java final
modifier?
Edit: I am especially interested in the case where the base class of the derived class has a virtual
destructor.
Are there any circumstances in which it is legitimate for a derived class to have a non-virtual destructor?
Yes.
A non-virtual destructor signifies that a class should not be used as a base-class.
Not really; a non-virtual destructor signifies that deleting an instance of derived
via a base
pointer will not work. For example:
class Base {};
class Derived : public Base {};
Base* b = new Derived;
delete b; // Does not call Derived's destructor!
If you don't do delete
in the above manner, then it will be fine. But if that's the case, then you would probably be using composition and not inheritance.
Will having a non-virtual destructor of a derived class act like a weak form of the Java final modifier?
No, because virtual
-ness propagates to derived classes.
class Base
{
public:
virtual ~Base() {}
virtual void Foo() {};
};
class Derived : public Base
{
public:
~Derived() {} // Will also be virtual
void Foo() {}; // Will also be virtual
};
There isn't a built-in language mechanism in C++ to prevent subclasses. Which isn't much of an issue anyway since you should always prefer composition over inheritance. That is, use inheritance when a "is-a" relationship makes more sense than a true "has-a" relationship.
这篇关于具有非虚拟析构函数的派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!