如下代码:
#include <iostream>
using namespace std;
class A13 {
public:
A13() {
cout << "default constructor" << endl;
}
int say() {
cout << "say" << endl;
return 0;
}
};
class B: public A13 {
};
int main() {
B *b = new B();
b->say();
delete b;
return 0;
}
B 继承A ,编译以及运行都正常。
如果我们现在把第三行由:
class A13 {
修改为
class A13 final {
编译错误如下:
cpp13.cpp:15:7: error: cannot derive from ‘final’ base ‘A13’ in derived type ‘B’
15 | class B: public A13 {
| ^
由于 class A13 之后有加 final ,表明这个类不能被继承,所以编译报错。
最终全部代码如下:
#include <iostream>
using namespace std;
class A13 final {
public:
A13() {
cout << "default constructor" << endl;
}
int say() {
cout << "say" << endl;
return 0;
}
};
class B: public A13 {
};
int main() {
B *b = new B();
b->say();
delete b;
return 0;
}
如下代码B14继承A14,编译运行都正常,
#include <iostream>
using namespace std;
class A14 {
public:
A14() {
cout << "default constructor A14" << endl;
}
virtual int say() {
cout << "A say" << endl;
return 0;
}
};
class B14: public A14 {
public:
int say() {
cout << "B say" << endl;
return 0;
}
};
int main() {
B14 *b = new B14();
b->say();
delete b;
return 0;
}
如果我们将虚函数
virtual int say()
后面加 final:
virtual int say() final {
则编译错误如下:
cpp14.cpp:18:14: error: virtual function ‘virtual int B14::say()’ overriding final function
18 | int say() {
| ^~~
cpp14.cpp:9:21: note: overridden function is ‘virtual int A14::say()’
9 | virtual int say() final {
| ^~~
表明虚函数加final 之后不能被覆盖重写。
最终的完整代码如下:
#include <iostream>
using namespace std;
class A14 {
public:
A14() {
cout << "default constructor A14" << endl;
}
virtual int say() final {
cout << "A say" << endl;
return 0;
}
};
class B14: public A14 {
public:
int say() {
cout << "B say" << endl;
return 0;
}
};
int main() {
B14 *b = new B14();
b->say();
delete b;
return 0;
}
当然一个非虚函数加final 也编译报错,final用在函数上的时候,只能用在虚函数上。