“虚拟”关键字或不在子类中声明继承的虚函数之间有什么区别吗,考虑到我想调用适合我的对象的乐趣'类型。看看评论。
#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;
}
最佳答案
如果基类中的相应函数是虚拟的,则派生类中的覆盖函数被隐式声明为“虚拟”。只需确保您获得完全相同的签名,否则您可能会无意中隐藏原始函数并声明一个新函数!
在 C++0x 中,可以随意使用 override
说明符。
你的两个“为什么?”问题是因为切片;你正在制作类型为 A
的新的复制切片对象.请注意,在 B x; static_cast<A>(x);
Actor 阵容和说的一样A(x)
.
关于c++ - 虚函数关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7054180/