虚拟功能关键字 [英] Virtual function keyword
问题描述
在子类中声明继承的虚函数与虚关键字或不是之间有任何区别,考虑到我想调用适合于我的对象的乐趣'类型。看看评论。
Is there any difference between declaring inherited virtual function in a child class with the "virtual" keyword or not, considering I want to call fun appropriate to my objects' type. Look at the comments.
#include <cstdio>
struct A{
int a;
A():a(5){}
virtual int fun(){return a+1;}
};
struct B: public A{
virtual int fun(){return a+5;} //I put virtual here
// int fun(){return a+5;} // Any difference if I put virtual before or not?
};
int main(){
B obj;
printf("%d\n", static_cast<A>(obj).fun()); // A::fun() called. Why?
printf("%d\n", static_cast<A&>(obj).fun()); // B::fun() called. As expected
printf("%d\n", static_cast<A*>(&obj)->fun()); // B::fun() called. As expected
printf("%d\n", static_cast<A>(B()).fun()); // A::fun() again. Why?
// printf("%d\n", static_cast<A&>(B()).fun()); //invalid_cast error. Why?
printf("%d\n", static_cast<A*>(&B())->fun()); //It works! B::fun() call
return 0;
}
推荐答案
派生类中的覆盖函数如果基类中的对应函数是虚拟的,则隐式声明为虚拟。只要确保你得到了完全相同的签名,或者你可能会无意中隐藏原始函数并声明一个新的函数!
Overriding functions in derived classes are implicitly declared "virtual" if the corresponding function in the base class is virtual. Just make sure you got the exact same signature, or you might inadvertently hide the original function and declare a new one!
在C ++ 0x中,使用覆盖
说明符。
In C++0x, feel free to make liberal use of the override
specifier.
您的两个为什么?问题是由于切片;您正在创建类型为 A
的新复制切片对象。请注意,在 B x; static_cast< A>(x);
演员阵容与
Your two "Why?" questions are because of slicing; you're making new, copy-sliced objects of type A
. Note that in B x; static_cast<A>(x);
the cast is the same as saying A(x)
.
这篇关于虚拟功能关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!