C++const修饰的虚函数
在C++中,对于两个函数,一个有const修饰,一个没有const修饰,认为这两个函数是不同的函数。
虚函数的要求是,函数原型相同,函数原型包括:函数返回值、函数名、参数列表、const修饰符。这里const修饰符包括函数返回值的修饰,函数形参的修饰,函数本身的修饰。只要有一处没有对上 ,那么就不是虚函数的override,而是调用基类的同名函数。
所以对于基类的cosnt虚函数,如果子类重写忘记加上const,编译器会认为是基类的函数。
如下列代码:
1 #include <iostream> 2 using namespace std; 3 4 class Father 5 { 6 public: 7 virtual void show()const 8 { 9 cout << "this is Father." << endl; 10 } 11 }; 12 13 class Son: public Father 14 { 15 public: 16 virtual void show() // 没有const 该函数为Son的虚函数,只有Son以及其子类才拥有,和Father没关系 17 { 18 cout << "this is Son." << endl; 19 } 20 }; 21 22 void main() 23 { 24 Father*p = new Father; 25 p->show(); // 输出 "this is Father" 26 p = new Son; 27 p->show(); // 输出 "this is Father" 28 }
那如果基类虚函数结尾是const = 0,而子类没有添加const会怎么样?那么使用该子类的时候编译器将报错,不让你编译通过。
扩展一下,假如在子类实现了父类的const虚函数,并且声明一个同名未加const的函数,那么子类该如何调用两个同名函数?代码如下
1 #include <iostream> 2 using namespace std; 3 4 class Father 5 { 6 public: 7 virtual void show()const 8 { 9 cout << "this is Father." << endl; 10 } 11 }; 12 13 class Son: public Father 14 { 15 public: 16 virtual void show() // 没有const 17 { 18 cout << "this is Son." << endl; 19 } 20 21 virtual void show() const 22 { 23 cout<<"this is no const Son."<<endl; 24 } 25 }; 26 27 void main() 28 { 29 p1 = new Son; 30 p1->show(); // 输出 "this is Son" 31 32 const p2 = new Son; // 加了const 33 p2->show(); // 输出 "this is no const Son" 34 35 }