在下面的代码中,为什么最后一次调用eat()关于参考c返回 ”动物 b 正在吃东西。“?据我了解,c是对实例的引用b派生类的Dog and eat()是一个虚函数。所以它应该已经返回“狗b正在吃东西。”
#include <string>
#include <iostream>
using namespace std;
class Animal
{
protected:
string name;
public:
Animal( string _name ):
name(_name)
{
}
virtual void eat()
{
cout << "An animal " << name << " is eating." << endl;
}
};
class Dog : public Animal
{
public:
Dog( string _name ):
Animal(_name)
{
}
void eat()
{
cout << "A dog " << name << " is eating." << endl;
}
};
int main( int argc , char ** argv )
{
Animal a("A");
a.eat();
Dog b("b");
b.eat();
Animal & c = a;
c.eat();
c = b;
c.eat();
return 0;
}
这是输出:
An animal A is eating.
A dog b is eating.
An animal A is eating.
An animal b is eating.
Animal & c = a;
c.eat();
c = b; ///^^^
c.eat();
在 C++ 中,引用一旦初始化就不能重新绑定到其他对象。c
仍然是对象的别名a
,这是一个Animal
,因此,您看到了预期的输出。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)