链接:final 说明符 (C++11 起) - cppreference.com
目录
final的使用
1、不能使用 "final" 修饰符声明非虚函数
struct Base
{
virtual void foo();
};
struct A : public Base
{
void foo() final; // Base::foo 被覆盖而 A::foo 是最终覆盖函数
void bar() final; // 错误:bar 非虚,因此它不能是 final 的
// 不能使用 "final" 修饰符声明非虚函数
};
void A::foo()
{
}
2、无法重写基类的“final”函数 "A::foo"
struct B final : A // struct B 为 final
{
void foo() override; // 错误:foo 不能被覆盖,因为它在 A 中是 final 的
// 无法重写“final”函数 "A::foo"
};
3、不能将“final”类类型用作基类
struct C : B{}; // 错误:B 是 final 的
//不能将“final”类类型用作基类
override 的使用 : 重写父类的虚函数
C++11标准添加了一个override关键字放在派生类的虚函数后,如果编译器发现派生类重写的虚函数与基类的虚函数不一样(参数或其他不一样的地方),那么编译器将报错
放在子类重写父类的方法声明的末尾,用来检测重写的方法的正确性