C++final关键字作用

1、类被标记为final,禁止被继承

class base final
{};

class derived: public base    // 报错,不能将"final"类型作为基类
{};

 

2、虚函数(函数必须是虚函数)被标记final,禁止被 override

class base
{
    virtual void show() final { cout << "this is base" << endl; }
};

class derived : public base
{
    void show() { cout << "this is derived" << endl; }
        //  error:declaration of 'show' overrides a 'final' function(把override翻译成“重写”总感觉很矛盾)
};

 

posted @ 2021-12-28 18:08  补码  阅读(340)  评论(0编辑  收藏  举报