在子类中声明继承的虚函数有什么区别with“虚拟”关键字or not,考虑到我想调用适合我的对象类型的 fun 。看看评论。
#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
说明符。
你的两个“为什么?”问题是因为slicing;你正在创建新的、复制切片类型的对象A
。请注意,在B x; static_cast<A>(x);
演员阵容和说的一样A(x)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)