添加纯虚析构函数定义的目的是什么?
灵感来源:C++——为什么我们应该在类定义之外定义纯虚析构函数?
下面的代码实际上做了什么?
class Object
{
public:
virtual ~Object() = 0;
};
Object::~Object() { /*...*/ }
我认为纯虚函数的目的是强制子类实现该特定函数。如果是这样的话,那为什么还要在虚拟基类中实现相同的功能呢?
Inspired by: C++ -- why should we define the pure virtual destructor outside the class definition?
What does the following code actually do?
class Object
{
public:
virtual ~Object() = 0;
};
Object::~Object() { /*...*/ }
I thought that the point of a pure virtual function was to force subclasses to implement that particular function. If that is the case, then why bother implementing the same function in the virtual base class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此代码阻止您创建 Object 实例,同时允许您创建子类。
销毁对象时,会调用父类的析构函数,因此它必须存在。无论析构函数是否是纯虚拟的,这都适用。仅当显式调用纯虚拟成员函数时,才需要定义它,
Foo:theFunc()
。This code prevents you from creating an instance of Object, while at the same time allowing you to create subclasses.
When destroying an object, the destructor of the parent class will be called, so it must exist. This applies whether the destructor is pure virtual or not. A pure virtual member function only needs to be defined if you explicitly call it,
Foo:theFunc()
.对于纯虚拟析构函数,没有办法“强迫”任何人在派生类中实现它。编译器会为你写一个。此外,编译器编写的析构函数(在派生类中)将调用父析构函数 - 因此您最好为父代编写一个实现。
因此,总结一下:
In the case of a pure virtual destructor, there is no way of 'forcing' anyone to implement it in derived classes. The compiler will write one for you. In addition, the compiler written destructor (in a derived class) will call the parent destructor - so you had better have written an implementation for the parent.
So, to summarise: