纯虚函数与抽象类

纯虚函数一般是基类中定义的,派生类中必需重定义,不然是缺损的。虚函数一般是一个共有的的成员函数,方便理解

详见代码:

View Code
#include <iostream>
using namespace std;

class Animal {
public:
    virtual void eat() = 0;//纯虚函数,只能用指针声明
    void sleep(){
        cout << "睡觉" << endl;
    }
};

class Rabbit:public Animal
{
public:
    void eat()//子类必需对纯虚函数进行重定义,不然不能声明这个类
    {
        cout << "兔子吃草" << endl;
    }
};

class Tiger:public Animal
{
public:
    void eat() //同理
    {
        cout << "老虎吃肉" << endl;
    }
};

int main() {
    Animal *p;
    Rabbit ra;
    Tiger ta;
    p = &ra;
    p->eat();
    p->sleep();
    p = &ta;
    p->eat();
    p->sleep();
    return 0;
}
原文地址:https://www.cnblogs.com/gray035/p/3025019.html