C ++纯虚函数有体 [英] C++ pure virtual function have body
问题描述
纯虚函数(当我们设置 = 0
时)也可以有一个函数体。
Pure virtual functions (when we set = 0
) can also have a function body.
推荐答案
你的假设是:纯虚函数不能被调用是绝对不正确的。当一个函数被声明为纯虚函数时,它只是意味着这个函数不能通过虚拟调度机制动态调用。然而,这个非常相同的函数可以容易地被静态地调用 ,而没有虚拟分派。
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, without virtual dispatch.
在C ++语言中当在调用中使用函数的限定名时,即在调用中指定的函数名具有< class name> ::< function name>
form。
In C++ language static 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.
$ b
For example
struct S {
virtual void foo() = 0;
};
void S::foo() {
// body for the pure virtual function `S::foo`
}
struct D : S {
void foo() {
S::foo(); // static call to `S::foo` from derived class
}
};
int main() {
D d;
d.S::foo(); // another static call to `S::foo`
}
这篇关于C ++纯虚函数有体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!