纯虚函数

来源:互联网 发布:网络文明调查数据 编辑:程序博客网 时间:2024/05/05 03:31
//含有纯虚函数的类不能实例化对象//只有当这个函数在子类中实现之后,才能实例化对象   //用处:当某个行为是必须的,但对于不同的对象具体的实现方法不同(如animal中breathe的方式不同)//可在父类中将其设置为纯虚函数//然后再子类中具体实现#include<iostream>using namespace std;class animal{public:    animal(int hight, int weight)    {        //cout << "animal construct" << endl;    }    ~animal()    {        //cout << "animal deconstruct" << endl;    }    void eat()    {        cout << "animal eat" << endl;    }    void sleep()    {        cout << "animal sleep" << endl;    }    virtual void breathe() = 0;//纯虚函数//  {//      cout << "animal breathe" << endl;//  }};class fish :public animal {public:    fish() : animal(400, 300), a(1)    {        //cout << "fish construct" << endl;    }    ~fish()    {        //cout << "fish deconstruct" << endl;    }    void breathe()    {        //animal::breathe();// :: 叫做作用域标识符,表示函数所属的类        cout << "fish bubble" << endl;    }private:    const int a;};void fn(animal *pan){    pan->breathe();}int main(){    fish fh; //在产生fish时先构造animal,在构造fish剩余的部分    animal *pan;    pan = &fh;//将fish对象的地址转换成animal的指针,看内存布局     fn(pan);    return 0;}
0 0
原创粉丝点击