C++中增加了final关键字来限制某个类不能被继承,或者某个虚函数不能被重写,这和Java的final关键字的功能类似;但是java中的final可以修饰变量,C++中的是不能的(后续会有对比)。
final只能修饰虚函数,并且要把final关键字放到类或者函数的后面。
#include<iostream> using namespace std; class Base { public: virtual void test() { //虚函数 cout << "Base class " << endl; } virtual void test1() = 0; //纯虚函数 }; class Chile :public Base { public: void test() final { cout << "Chile class...." << endl; } void test1() final { cout << "Chile 纯虚test" << endl; } //void hello() final { //报错,final不能修饰一个非虚的函数 // cout << "hello " << endl; //} }; class GrandChile : public Chile { public: //void test() { //Chile中的test已经是final的,不能再被重写了。 // cout << "GrandChile class...." << endl; //} //void test1() { //Chile中的test已经是final的,不能再被重写了。 // cout << "GrandChile 纯虚test" << endl; //} }; int main() { return 0; }final限制某个类不能被继承:
class Chile final:public Base { public: }; class GrandChile : public Chile { //这里就会报错,Chile不能被继承 public: };