C++中const用於函數重載


C++中const用於函數重載

常成員函數和非常成員函數之間的重載

首先先回憶一下常成員函數

聲明:<類型標志符>函數名(參數表)const;

說明:

(1)const是函數類型的一部分,在實現部分也要帶該關鍵字。

(2)const關鍵字可以用於對重載函數的區分。

(3)常成員函數不能更新類的成員變量,也不能調用該類中沒有用const修飾的成員函數,只能調用常成員函數。

(4)非常量對象也可以調用常成員函數,但是如果有重載的非常成員函數則會調用非常成員函數

 

重載看例子:

#include<iostream>  
using namespace std;  
   
class Test  
{  
protected:  
    int x;  
public:  
    Test (int i):x(i) { }  
    void fun() const  
    {  
        cout << "fun() const called " << endl;  
    }  
    void fun()  
    {  
        cout << "fun() called " << endl;  
    }  
};  
   
int main()  
{  
    Test t1 (10);  
    const Test t2 (20);  
    t1.fun();  
    t2.fun();  
    return 0;  
}  

 

結果為:

 

 

const修飾成員函數時的重載

分兩種情況,一種情況下不允許重載,另一種允許。還是直接看例子吧:

#include<iostream>  
using namespace std;  

void fun(const int i)  
{  
    cout << "fun(const int) called ";  
}  
void fun(int i)  
{  
    cout << "fun(int ) called " ;  
}  
int main()  
{  
    const int i = 10;  
    fun(i);  
    return 0;  
}  

 

結果:編譯錯誤,提示重定義:

 

 

其實很好理解

void fun(int a)和

void fun(const int a);

實際上沒有區別,因為函數調用的時候,存在形實結合的過程,所以不管有沒有const都不會改變實參的值。

 

但是看下面的情況:

#include<iostream>  
using namespace std;  
   
void fun(char *a)  
{  
  cout << "non-const fun() " << a;  
}  
   
void fun(const char *a)  
{  
  cout << "const fun() " << a;  
}  
   
int main()  
{  
  const char *ptr = "hello world";  
  fun(ptr);  
  return 0;  
}  

 

結果:通過編譯,且輸出結果為:

 

 

很奇怪是嗎,這種情況和上面的情況難道不一樣嗎?

先別急,再來看一個例子。然后再解釋。

#include<iostream>  
using namespace std;  
   
void fun(char *a)  
{  
  cout << "non-const fun() " << a;  
}  
   
void fun(char * const a)  
{  
  cout << "const fun() " << a;  
}  
   
int main()  
{  
  char ptr[] = "hello world";  
  fun(ptr);  
  return 0;  
}  

 

結果:編譯不通過,提示重定義:

 

好了,現在解釋原因。

 

第一個例子中,我們說,fun(int i)和fun(const int i)是一樣的,是因為函數調用中存在實參和形參的結合。加入我們用的實參是int a,那么這兩個函數都不會改變a的值,這兩個函數對於a來說是沒有任何區別的,所以不能通過編譯,提示重定義。

好了,那 fun(char *a)和fun(const char *a)是一樣的嗎?答案是:不一樣。因為char *a 中a指向的是一個字符串變量,而const char *a指向的是一個字符串常量,所以當參數為字符串常量時,調用第二個函數,而當函數是字符串變量時,調用第一個函數。

但是char *a和char * const a,這兩個都是指向字符串變量,不同的是char *a是指針變量 而char *const a是指針常量,這就和int i和const int i的關系一樣了,所以也會提示重定義。

最后說一下,對於引用,比如int &i 和const int & i 也是可以重載的,原因是第一個i引用的是一個變量,而第二個i引用的是一個常量,兩者是不一樣的,類似於上面的指向變量的指針的指向常量的指針。

下面是例子:

#include<iostream>  
using namespace std;  
   
void fun(const int &i)  
{  
    cout << "fun(const int &) called  "<<endl;  
}  
void fun(int &i)  
{  
    cout << "fun(int &) called "<<endl ;  
}  
int main()  
{  
    const int i = 10;  
    fun(i);  
    return 0;  
}  

 

結果為:

 

最后謝謝,水草的專欄

http://blog.csdn.net/shltsh/article/details/45939977

感謝分享

如果你覺得對你有用,請贊一個吧~~~


免責聲明!

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



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