在下面的代码,为什么的最后通话吃(ç回报“动物b为食。”?从我的理解,Ç是实例b派生类狗和吃的()的参考是一个虚拟函数。所以它应该返回“狗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.
我看不出参考'D'在你的代码。 – taocp
@taocp,对不起,它是c,不是d。我已经修好了。 –
3个答案在12秒内.... :) – dyp