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 }    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM