赞
踩
C++中,当子类重写了基类的虚函数时,编译器不会对函数签名的一致性做判断,而这有可能造成一些似是而非的错误:
- #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)//函数签名与基类不一致(拼写错误)
- {
- cout<<"make phone call to "<<phoneNumber<<" by smart phone"<<endl;
- }
- };
-
-
- int main()
- {
- SmartPhone phone;
- phone.makeCall("123456"); //调用基类的函数,输出:make phone call to 123456
- phone.makecall("123456"); //调用子类的函数,输出:make phone call to 123456 by smart phone
- return 0;
- }
-
- 子类SmartPhone原本是要重写基类的makeCall,但却拼写错误,后果是实际上重新声明了一个函数makecall,并没有重写基类的makeCall
C++11增加了关键字override,明确的指出这是一个对虚函数重写,编译器会严格的对函数签名进行检
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。