Chinaunix首页 | 论坛 | 博客
  • 博客访问: 16200
  • 博文数量: 14
  • 博客积分: 245
  • 博客等级: 二等列兵
  • 技术积分: 180
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-28 13:45
文章分类

全部博文(14)

文章存档

2013年(9)

2012年(5)

我的朋友

分类: C/C++

2012-12-31 11:11:45

#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) |
给主人留下些什么吧!~~