C++纯虚函数有函数体
纯虚函数(当我们设置= 0
时)也可以有一个函数体。
如果纯虚函数根本不会被调用,那么为它们提供函数体有什么用呢?
Pure virtual functions (when we set = 0
) can also have a function body.
What is the use to provide a function body for pure virtual functions, if they are not going to be called at all?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您认为无法调用纯虚函数的假设是绝对错误的。当一个函数被声明为纯虚函数时,它仅仅意味着该函数无法通过虚拟调度机制动态调用。然而,这个完全相同的函数可以轻松地静态、非虚拟、直接调用(无需虚拟调度)。
在C++语言中,当在调用中使用函数的限定名称时,即当在调用中指定的函数名称具有
::<;时,执行对虚函数的非虚拟调用。函数名>
形式。例如
Your assumption that pure virtual function cannot be called is absolutely incorrect. When a function is declared pure virtual, it simply means that this function cannot get called dynamically, through a virtual dispatch mechanism. Yet, this very same function can easily be called statically, non-virtually, directly (without virtual dispatch).
In C++ language a non-virtual call to a virtual function is performed when a qualified name of the function is used in the call, i.e. when the function name specified in the call has the
<class name>::<function name>
form.For example
请参阅此处。
see here.
对于大多数纯虚函数,你是对的。然而,对于纯虚析构函数来说,定义相应的析构函数实现实际上很重要:
For most pure virtual functions, you'd be right. However, for a pure virtual destructor, it's actually important to define a corresponding destructor implementation: