#include "stdafx.h"
#include
using namespace std;
class animal
{
public:
virtual void eat() = 0;
};
class bird : public animal
{
public:
virtual void eat();
};
class beast: public animal
{
public:
virtual void eat();
};
class cock:public bird
{
public:
virtual void eat();
};
class duck:public bird
{
public:
virtual void eat();
};
class horse:public beast
{
public:
virtual void eat();
};
class cat:public beast
{
public:
virtual void eat();
};
void animalEatWhat(animal* a_animal)
{
a_animal->eat();
}
void bird::eat()
{
cout<<"bird is eating some small thing"<}
void beast::eat()
{
cout<<"beast is eating some big thing"<}
void cock::eat()
{
cout<<"cock is eating bread"<}
void duck::eat()
{
cout<<"duck is eating fish"<}
void horse::eat()
{
cout<<"horse is eating grass"<}
void cat::eat()
{
cout<<"cat is eating moss"<}
int _tmain(int argc, _TCHAR* argv[])
{
bird a_bird;
beast a_beast;
cock a_cock;
duck a_duck;
horse a_horse;
cat a_cat;
animalEatWhat(&a_bird);
animalEatWhat(&a_beast);
animalEatWhat(&a_cock);
animalEatWhat(&a_duck);
animalEatWhat(&a_horse);
animalEatWhat(&a_cat);
return 0;
}
1、这里用到了虚函数,和纯虚函数。虚函数、多态、动态联编是一个概念。
2、为什么要用多态呢? 多态是C++典型的特性,最大的好处的接口的通用化。我们这里的一个接口animalEatWhat(animal* a_animal),就可以给6个不同的类来使用。 而不需要去写六个类似的函数。
3、虚函数纯粹作为接口,只声明不定义。虚函数可以声明可以定义。
4、程序的运行结果如下:
bird is eating some small thing
beast is eating some big thing
cock is eating bread
duck is eating fish
horse is eating grass
cat is eating moss
请按任意键继续. . .
阅读(451) | 评论(0) | 转发(0) |