C++ 纯虚函数有函数体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5481941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ pure virtual function have body
提问by Vijay
Pure virtual functions (when we set = 0
) can also have a function body.
纯虚函数(当我们设置时= 0
)也可以有一个函数体。
What is the use to provide a function body for pure virtual functions, if they are not going get called at all?
如果它们根本不会被调用,那么为纯虚函数提供函数体有什么用?
回答by AnT
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.
在 C++ 语言中,当在调用中使用函数的限定名称时,即当调用中指定的函数名称具有以下<class name>::<function name>
形式时,会执行对虚函数的非虚拟调用。
For example
例如
struct S
{
virtual void foo() = 0;
};
void S::foo()
{
// body for pure virtual function `S::foo`
}
struct D : S
{
void foo()
{
S::foo();
// Non-virtual call to `S::foo` from derived class
this->S::foo();
// Alternative syntax to perform the same non-virtual call
// to `S::foo` from derived class
}
};
int main()
{
D d;
d.S::foo();
// Another non-virtual call to `S::foo`
}
回答by Prince John Wesley
"Effective C++" Meyers mentions a reason for a pure virtual function to have a body: Derived classes that implement this pure virtual function may call this implementation smwhere in their code. If part of the code of two different derived classes is similar then it makes sense to move it up in the hierarchy, even if the function should be pure virtual.
“Effective C++” Meyers 提到了一个纯虚函数有一个主体的原因:实现这个纯虚函数的派生类可能会在他们的代码中调用这个实现。如果两个不同派生类的部分代码相似,那么将其在层次结构中向上移动是有意义的,即使函数应该是纯虚拟的。
see here.
看到这里。
回答by Chris Jester-Young
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:
对于大多数纯虚函数,您是对的。但是,对于纯虚拟析构函数,定义相应的析构函数实现实际上很重要:
- The "pure virtual" is to require derived classes to implement their destructor.
- Your base class destructor implementation is so that the derived class destructors can successfully "chain up" afterwards.
- “纯虚拟”是要求派生类实现其析构函数。
- 您的基类析构函数实现是为了使派生类析构函数之后可以成功“链接”。