我有两个类:问虚函数
class x {
public:
virtual void hello() {
std::cout << "x" << std::endl;
}
};
class y : public x {
public:
void hello() {
std::cout << "y" << std::endl;
}
};
有人可以解释为什么以下两个调用为hello()打印不同的消息?他们为什么不打印“y”?是因为第一个是副本,而第二个实际指向内存中的对象?
int main() {
y a;
x b = a;
b.hello(); // prints x
x* c = &a;
c->hello(); // prints y
return 0;
}
我觉得这是我第一次看到有人正确猜出原因,做得不错。 – GManNickG 2011-01-28 07:02:47