2011-09-14 54 views
42

一個相當理論上的問題......爲什麼常量引用不像常量指針那樣運行,我實際上可以改變它們指向的對象?他們看起來像另一個簡單的變量聲明。爲什麼我會使用它們?這是我運行的編譯和運行沒有錯誤很短的例子:什麼是常量引用? (不是對常量的引用)

int main(){ 
    int i=0; 
    int y=1;  
    int&const icr=i; 
    icr=y;   // Can change the object it is pointing to so it's not like a const pointer... 
    icr=99;   // Can assign another value but the value is not assigned to y... 
    int x=9; 
    icr=x; 
    cout<<"icr: "<<icr<<", y:"<<y<<endl; 
} 
+4

看'之前和之後'ICR = Y i';'。 –

+3

一個不變的參考是...廢話。 :) – jalf

+2

這是否甚至編譯? –

回答

53

最明確的答案。 Does 「X& const x」 make any sense?

No, it is nonsense

To find out what the above declaration means, read it right-to-left: 「x is a const reference to a X」. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.

In other words, 「X& const x」 is functionally equivalent to 「X& x」. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said 「const X& x」.

43

聲明icr=y;不作參考參考y;它將值y分配給icr所指的變量,i

參考文獻本質上是const,即您無法更改它們所指的內容。有'const引用'這實際上是'const'的引用,即你不能改變它們引用的對象的值。儘管如此,它們被宣佈爲const int&int const&而不是int& const

+0

因此,對const的引用也可以看作是對const的常量引用?這現在很有意義。 – Dasaru

+1

@Dasaru: 是的,它可以,但是對非const的引用也可以看作是對非const的一個常量引用,因爲引用本身總是const,與引用const的引用無關。 – Kaiserludi

23

什麼是恆定的參考(而不是一個常數的引用)
恆定參考實際上是一個參考到恆定

恆定的參考/參考到常數由表示:

int const &i = j; //or Alternatively 
const int &i = j; 
i = 1;   //Compilation Error 

這基本上意味着,不能修改到的引用所引用對象的類型的值。
例如:
試圖修改值(分配1)可變j通過const引用的,i將導致錯誤:

assignment of read-only reference ‘i’


icr=y;   // Can change the object it is pointing to so it's not like a const pointer... 
icr=99; 

不改變參考,它分配該參考涉及的類型的值。 引用不能引用除初始化時綁定的變量之外的任何其他變量。

首先聲明受讓人我猜你真的是「參考常量數據」的價值yi
第二條語句受讓人99i

+0

如何以及爲什麼聲明像const int & a=3;有效? – Destructor

+3

等待,'const類型&'相當於'類型const&'? – Tyler

+0

@泰勒,是的,它是 –

3

通過「恆定的參考」。另一方面,指針可以是一個常量指針(指針本身是常量,而不是它指向的數據),指向常數數據的指針或兩者。

+0

示例代碼實際上是指一個常量引用('int&const icr = i;')而不是對常量的引用。 – Void

+0

我認爲海報並不清楚,因爲常量被放置在代碼中。 – Poodlehat