在下面的代碼,爲什麼的最後通話吃(ç回報「動物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