纯虚函数

  • 纯虚函数所在的类(接口)不能被实例化,因为这个函数没有定义。
  • 纯虚函数没有定义,函数交给派生类去定义。
  • 派生类必须实现基类中的纯虚函数。
virtual xxx funName(xxx) = 0; // 纯虚函数

Talk is cheap. Show me the code.

#include <iostream>

using namespace std;

class Api{
public:
    virtual string getClassName() = 0; // 纯虚函数
};

class Logs: public Api{
    string getClassName() override{
        return "Logs";
    }
};

class Player: public Api{
    string getClassName() override{
        return "Player";
    }
};

void printClassName(Api *p_api){
    cout << p_api->getClassName() << endl;
}

int main()
{
    Logs *console = new Logs();
    Player player;
    printClassName(console);
    printClassName(&player);
    return 0;
}

代码中 Api 类中有一个获取类名的纯虚函数。 LogsPlayer 类都继承了 Api 类。

所以 LogsPlayer 必须实现获取类名的功能。


引入原因

1、为了方便使用多态特性,我们常常需要在基类中定义虚函数。

2、在很多情况下,基类本身生成对象是不合情理的。例如,动物作为一个基类可以派生出老虎,孔雀等子类,但动物本身生成对象明显不合常理。

最后修改:2023 年 04 月 28 日
如果觉得我的文章对你有用,请随意赞赏