簡單來說virtual function如果子類別有實作則會執行子類別中的內容,
如果不是virtual function,即使子類別有實作,還是會執行父類別中的內容。
/*****************************************************/
void FeedFood(*Animal animal)
{
animal->eat();
}
class Animal
{
public:
void eat()
{
cout << "eat generic food." << endl;
}
}
class Cat : public Animal
{
public:
void eat()
{
cout << "eat fish." << endl;
}
}
Animal *animal = new Animal;
Cat *cat = new Cat;
animal -> eat(); // eat generic food.
cat -> eat(); // eat fish.
FeedFood(animal); // eat generic food.
FeedFood(cat); // eat generic food.
/*****************************************************/
void FeedFood(*Animal animal)
{
animal->eat();
}
class Animal
{
public:
virtual void eat()
{
cout << "eat generic food." << endl;
}
}
class Cat : public Animal
{
public:
void eat()
{
cout << "eat fish." << endl;
}
}
FeedFood(animal); // eat generic food.
FeedFood(cat); // eat fish.
沒有留言:
張貼留言