final
C++ 中增加了 final
关键字来限制某个类不能被继承,或者某个虚函数不能被重写。如果使用 final
修饰函数,只能修饰虚函数,并且要把 final
关键字放到类或者函数的后面。
修饰函数
如果使用 final
修饰函数,只能修饰虚函数,这样就能阻止子类重写父类的这个函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Base { public: virtual void test() { cout << "Base class..." << endl; } };
class Child : public Base { public: void test() final { cout << "Child class..." << endl; } };
class GrandChild : public Child { public: void test() { cout << "GrandChild class..." << endl; } };
|
上面的代码中有三个类:基类 Base、子类 Child、孙子类 GrandChild。
test()
是基类中的一个虚函数,在子类中重写了这个方法,但是不希望孙子类中继续重写这个方法,因此在子类中将 test()
方法标记为 final
,孙子类中对这个方法不能重写、只能使用。
修饰类
使用 final
关键字修饰过的类是不允许被继承的,这个类不能有派生类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Base { public: virtual void test() { cout << "Base class..." << endl; } };
class Child final: public Base { public: void test() { cout << "Child class..." << endl; } };
class GrandChild : public Child { public: };
|
Child 类是被 final
修饰过的,因此 Child 类不允许有派生类 GrandChild 类继承。
override
override
关键字确保在派生类中声明的重写函数与基类的虚函数有相同的签名,同时也明确表明将会重写基类的虚函数,这样就可以保证重写的虚函数的正确性,也提高了代码的可读性,和 final
一样这个关键字要写到方法的后面。使用方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Base { public: virtual void test() { cout << "Base class..." << endl; } };
class Child : public Base { public: void test() override { cout << "Child class..." << endl; } };
class GrandChild : public Child { public: void test() override { cout << "GrandChild class..." << endl; } };
|
显示指定了要重写父类的 test()
方法,使用了 override
关键字之后,假设在重写过程中写错了函数名或者函数参数或者返回值,编译器都会提示语法错误,提高了程序的正确性,降低了出错的概率。
参考资料
https://subingwen.cn/cpp/final