final 和 override 两个关键字用于继承和多态
final: 修饰虚函数,表示该虚函数不能再被重写
#include <iostream>
// 基类 Base
class Base{
public:
// 被 final 修饰的虚函数不能再被重写
// 重写编译器会报错
virtual void func() final {
std::cout<<"void Base::func()"<<std::endl;
}
};
// 派生类 Derived
class Derived: public Base{
public:
void func(){
std::cout<<"void Derived::func()"<<std::endl;
}
};
int main(){
Base *p = new Derived();
std::cout << "p -> func() 输出:" << std::endl;
p -> func();
std::cout << std::endl;
return 0;
}
final: 修饰类,表示该类不能再被继承
如何实现一个不能被继承的类??
(1) C++98:把构造函数进行私有
(2) C++11:类定义时 加 final 关键字
#include <iostream>
// 基类 Base
class Base final {
public:
// 被 final 修饰的虚函数不能再被重写
// 重写编译器会报错
virtual void func() {
std::cout<<"void Base::func()"<<std::endl;
}
};
// 派生类 Derived
class Derived: public Base{
public:
void func(){
std::cout<<"void Derived::func()"<<std::endl;
}
};
int main(){
Base *p = new Derived();
std::cout << "p -> func() 输出:" << std::endl;
p -> func();
std::cout << std::endl;
return 0;
}
override: 修饰虚函数, 检查派生类虚函数是否重写了基类某个虚函数,如果没有重写编译报错
#include <iostream>
// 基类 Base
class Base{
public:
// 基类的虚函数
virtual void func() {
std::cout<<"void Base::func()"<<std::endl;
}
};
// 派生类 Derive
class Derive_01: public Base{
public:
// 派生类完成了虚函数的重写,编译通过
void func() override {
std::cout<<"void Derived::func()"<<std::endl;
}
};
// 派生类 Derive
class Derive_02: public Base{
public:
// 派生类没有重写基类虚函数,编译报错
void func(int n) override {
std::cout<<"void Derived::func()"<<std::endl;
}
};
int main(){
Base *p = new Derived();
std::cout << "p -> func() 输出:" << std::endl;
p -> func();
std::cout << std::endl;
return 0;
}