在下面的代码中,为什么最后一次调用引用c上的eat()会返回“ An animal b is eating. ”?据我了解,c是对派生类Dog的实例b的引用,而eat()是一个虚函数。所以它应该返回“A dog b is eating”。
#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.