虚函数问题 [英] Question with virtual functions
本文介绍了虚函数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个类:
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?是因为第一个是一个副本,而第二个实际上指向内存中的对象?
Can someone explain why the following two calls to hello() print different messages? Why don't they both print "y"? Is it because the first one is a copy while the second one actually points to the object in memory?
int main() {
y a;
x b = a;
b.hello(); // prints x
x* c = &a;
c->hello(); // prints y
return 0;
}
推荐答案
/ p>
Yes, you are right
x b = a;
调用复制构造函数(b IS a'x')
Invokes a copy constructor (b IS an 'x')
x& b = a;
分配引用并使用覆盖(b实际上是一个'y')
Assigns a reference and will use the override (b is still actually a 'y')
这篇关于虚函数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文