下面为代码示例:
#include<iostream.h>
class Animal{ //含有纯虚函数的类是抽象类,抽象类是不能实例化对象的
public:
Animal(int height,int weight){
//cout<<"animal construct"<<endl;
}
~Animal(){
//cout<<"animal disconstruct"<<endl;
}
void eat(){
cout<<"animal eat"<<endl;
}
void sleep(){
cout<<"animal sleep"<<endl;
}
virtual void breathe()=0; //纯虚函数
};
class Fish: public Animal{
public:
Fish():Animal(400,300),a(1){ //子类中向父类带参数的构造函数传递参数的一种方式
}
~Fish(){
}
void breathe()
{
//Animal::breathe(); // : 冒号是作用域标识符,主要用于表示是属于哪一个类的.
cout<<"fish bubble"<<endl;
}
private:
const int a; //常量是必须要进行初始化的
};
void fn(Animal *pAn){
pAn->breathe();
}
void main(){
Fish fs;
Animal *pAn;
pAn = &fs;
fn(pAn);
}
如果子类没有重新实现breathe函数的话,会出现错误,是由于Fish这个类没有实现基类的纯虚函数,所以它也变成了抽象类,故不能实例化对象。
纯虚函数存在的意义就是,我们在设计一个基类的时候,不好确定行为,将来的行为可能多种多样,而这种行为又是必须的,所以这个时候我们可以借助纯虚函数来设计,然后由派生类具体去实现它。