在C++中派生类可以重写基类中的虚函数,以覆盖基类中的操作。这种重写可以无限制的被后继承链的子类利用,C++11增加了final关键字用于终止虚函数的可重写性,也就是说从使用了final开始,后续的子类无法再重写这个虚函数:
#include <string>
#include <iostream>
using namespace std;
class Phone{
public:
virtual void makeCall(string phoneNumber)
{
cout<<"make phone call to "<<phoneNumber<<endl;
}
};
class SmartPhone : public Phone{
public:
void makeCall(string phoneNumber) final //final相当于为虚函数提供了一个最终版本,后续的子类不可对其再次重写
{
cout<<"make phone call to "<<phoneNumber<<" by smart phone"<<endl;
}
};
class IPhone : public SmartPhone{
public:
void makeCall(string phoneNumber) //由于SmartPhone使用了final,IPhone 无法对其进行重写,因此无法编译,编译输出: error: virtual function 'virtual void IPhone::makeCall(std::__cxx11::string)' overriding final function
{
cout<<"make phone call to "<<phoneNumber<<" by smart IPhone"<<endl;
}
};