[C++11] override 与 final

目录


overridefinal 是 c++11中的 说明符(specifier)

override


参考页面:https://zh.cppreference.com/w/cpp/language/override

作用:指定一个虚函数覆盖另一个虚函数。

class A
{
    virtual void foo();
    void bar();
};
 
class B : A
{
    void foo() const override; // 错误:B::foo 不覆盖 A::foo
                               // (签名不匹配)
    void foo() override; // OK:B::foo 覆盖 A::foo
    void bar() override; // 错误:A::bar 非虚
};

override作用是帮助检查是否继承了想要继承的虚函数。可以避免出现 “在继承的时候写错了函数(参数类型、参数个数不符),编译没问题但是程序运行时和预想的不一样” 的情况。
建议重写虚函数的时候加上 override

final


参考页面:https://zh.cppreference.com/w/cpp/language/final

作用:指定某个虚函数不能在子类中被覆盖,或者某个类不能被子类继承。

class Base
{
    virtual void foo();
};
 
class A : Base
{
    void foo() final; // Base::foo 被覆盖而 A::foo 是最终覆盖函数
    void bar() final; // 错误:非虚函数不能被覆盖或是 final
};
 
class B final : A // class B 为 final
{
    void foo() override; // 错误:foo 不能被覆盖,因为它在 A 中是 final
};
 
class C : B // 错误:B 为 final
{
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值