2015-10-15 92 views
-7

const關鍵字在C++中,我有一些麻煩了解其中使用const,這3種方式的區別:差異在C++

int get() const {return x;}   
const int& get() {return x;}  
const int& get() const {return x;} 

我想有例子來幫助我明白了一個明確的解釋差異。

+0

它已經在每個基本的C++教科書中得到很好的解釋。 –

回答

2

這裏是最const例如:

class Foo 
{ 
    const int * const get() const {return 0;} 
    \_______/ \___/  \___/ 
     |   |   ^-this means that the function can be called on a const object 
     |   ^-this means that the pointer that is returned is const itself 
     ^-this means that the pointer returned points to a const int  
}; 

你的具體情況

//returns some integer by copy; can be called on a const object: 
int get() const {return x;}   
//returns a const reference to some integer, can be called on non-cost objects: 
const int& get() {return x;}  
//returns a const reference to some integer, can be called on a const object: 
const int& get() const {return x;} 

This question介紹一點關於const成員函數。

Const參考也可以用於prolong the lifetime of temporaries

+0

不錯的答案,但我會擴大一點關於const成員函數的部分。它可以在const對象上調用,是的,但是我會補充說它是一個承諾,不會更改任何成員變量,也不會調用任何非const成員函數,並且此承諾由編譯器執行,如果違反,會發生錯誤。 –

+0

謝謝@SingerOfTheFall,我知道這是一個基本問題,但在我看來並不十分清楚 – Kruncho

0
(1) int get() const {return x;} 

這裏我們有兩種優點,

1. const and non-const class object can call this function. 

    const A obj1; 
    A obj1; 

    obj1.get(); 
    obj2.get(); 

    2. this function will not modify the member variables for the class 

    class A 
    { 
     public: 
     int a; 
     A() 
     { 
      a=0; 
     } 
     int get() const 
     { 
      a=20;   // error: increment of data-member 'A::a' in read-only structure 
      return x; 
     } 
    } 

雖然由常數函數改變類[A]的成員變量,編譯器會引發錯誤。

(2) const int& get() {return x;} 

將指針返回到常量整數引用。

(3)const int& get() const {return x;} 

它是組合答案(2)和(3)。