【发布时间】:2011-10-26 14:52:06
【问题描述】:
考虑到我想调用适合我的对象的乐趣'类型。看看cmets。
#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;
}
【问题讨论】:
-
最后的
&B()是编译器扩展,它不是有效的 C++。尝试找到将编译器置于一致模式的设置。 -
@Luc Compiler 警告我我取了临时地址,我认为没关系
-
你认为好的与否与什么是有效的 C++ 无关 :) 请注意,如果编译器确实警告过你,那么它是一个符合标准的编译器。您可以忽略我之前的评论(我强烈建议您编写有效的 C++)。
-
您可以临时参考非成本参考。倒数第二个可以是
printf("%d\n", static_cast<A const &>(B()).fun()); /* if you make fun() const */ -
@Luc 我想如果有什么东西放在内存中我可以/应该使用它:D
标签: c++ function inheritance virtual