2011-09-14 56 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