带有纯虚函数的类称为抽象类
纯虚函数与抽象类的作用:利用它可以创建模板;
优点:能够实现代码重复使用;
抽象类派生的派生类必须对这个抽象类中的纯虚函数重载,即使什么功能也不做,也要重载它,不然没有函数实体。
如果不在people.h中添加一下代码:
virtual void play()
{
;
}
会出现的错误信息是:
error C2259: 'people' : cannot instantiate abstract class due to following members:
d:\c text\5.22\practice3\people.h(5) : see declaration of 'people'
warning C4259: 'void __thiscall animal::play(void)' : pure virtual function was not defined
d:\c text\5.22\practice3\animal.h(20) : see declaration of 'play'
#ifndef _ANIMAL_H_ #define _ANIMAL_H_
#include <iostream.h> #include <string.h> #include <stdio.h>
class animal { public: char *name; public: animal(char *name1) { name=new char[strlen(name1)+1]; strcpy(name,name1); } virtual void sleep()=0; virtual void eat()=0; virtual void play()=0; ~animal() { delete name; } };
#endif
|
在抽象类(基类)中,定义了三个纯虚函数。这时需要在其派生类中重载纯虚函数。
#ifndef _PEOPLE_H_ #define _PEOPLE_H_ #include "animal.h"
class people:public animal { private: int age; public: people(char *name1,int age1):animal(name1) { age=age1; printf("Hello, I am %s!\n",name1); } virtual void sleep() { printf("people %s is sleeping....!\n",name); } virtual void eat() { printf("people %s is eating....!\n",name); } virtual void play() { ; } //纯虚函数play需要重载,即使什么功能也不做,也要重载它,不然没有函数实体
void play_with(animal &any) { printf("people %s is playing with %s ....!\n",name,any.name); any.play(); } };
#endif
|
#ifndef _CAT_H_ #define _CAT_H_ #include "animal.h"
class cat:public animal { public: cat(char *name1):animal(name1) { printf("Hello, I am %s! miao....\n",name1); } virtual void sleep() { printf("cat %s is sleeping....!\n",name); } virtual void eat() { printf("cat %s is eating....!\n",name); } virtual void play() { printf("cat %s is playing....! miaomiao..\n",name); } };
#endif
|
#include "animal.h" #include "cat.h" #include "dog.h" #include "people.h"
int main() { people Lee("Lee ming",20); cat kitty("kitty"); dog bruce("Bruce"); Lee.play_with(kitty); Lee.play_with(bruce); return 0; }
|
阅读(915) | 评论(0) | 转发(0) |