- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
在任何情况下派生类具有非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/
我是一名优秀的程序员,十分优秀!