苏州官方网站建站,在线制作视频网站,企业网站优化暴肃湖南岚鸿很好,汕头网站建设制作公司文章目录 1. override 关键字2. final 关键字在虚函数上使用 final在类上使用 final 1. override 关键字
用于明确表示派生类中的某个虚函数是用来重写基类中的虚函数的#xff0c;这样编译器会检查基类#xff0c;看看是否确实存在同样的虚函数#xff0c;如果没有匹配这样编译器会检查基类看看是否确实存在同样的虚函数如果没有匹配假设比对后发现参数类型、返回类型不同会报错。
这样有效防止了因为函数签名原型不一致带来的意外行为。 以下例子中print() 的参数类型不匹配在VISUALSTUDIO2022 直接红色波浪线在编译期即可检查出来
因此明示函数是重写的而非新定义的增加了代码的清晰度和可维护性。
class Base
{
public:virtual void show() const{cout Base::show endl;}virtual void print(int x)const{cout Base::print x endl;}
};class Derived :public Base
{
public:void show() const override // 正确重写{cout Derived::show endl;}void print(double x)const override // 错误重写参数类型不匹配{cout Derived::print x endl;}
};2. final 关键字
final 可以用在虚函数和类上
在虚函数上使用 final表示该函数在派生类中不能进一步被重写在类上使用 final , 表示该类不能被继承防止进一步派生
如果在设计时对于某些类或者虚函数不希望被进一步扩展或重写可以用 final 强制该约束避免不安全行为
在虚函数上使用 final
class Base
{
public:virtual void show() const {cout Base::show endl;}
};class Derived : public Base
{
public:void show() const final // 使用 final 禁止进一步重写{ cout Derived::show endl;}
};class MoreDerived : public Derived
{
public:void show() const override // 错误不能重写 final 函数{ cout MoreDerived::show endl;}
};Derived::show() 被标记为 finalMoreDerived 试图重写它带来编译错误
在类上使用 final
class Base final // 使用 final 表示该类不能被继承
{
public:void display() const {cout Base::display endl;}
};class Derived : public Base // 出现编译错误无法继承 final 类
{
};函数标记 final 后编译器可以进行优化因为它知道该函数不会被进一步重写适用于需要明确终止继承链的类和函数的时候