<分区>
Possible Duplicate:
const reference can be assigned an int?
有什么细微差别吗
const int& value = 12;
和
const int value = 12;
什么时候编译?怎么办?
<分区>
Possible Duplicate:
const reference can be assigned an int?
有什么细微差别吗
const int& value = 12;
和
const int value = 12;
什么时候编译?怎么办?
最佳答案
int value = 12;
这里'value'是值变量。
其中 int& 用于创建其他变量的引用变量(别名)。喜欢
int i;
int& j=i;
j 和 i 指的是相同的内存位置。 它是 c++ 概念。
但是不能为内存位置创建引用变量。所以在我看来,下面的表达式是错误提示
int& i = 12; `Will not compile even.`
关于const:
const 关键字用于创建只读变量。一旦初始化,变量的值就不能改变。考虑以下代码:
const int x = 2; // const var can be initialized, not modified thereafter
x = 10; // error - cannot modify const variable
错误:错误:只读变量'x'的赋值
表达式也可以在类型的两边都使用 const。
const int value = 12;
int const value = 12;
两个表达式相同(对于简单的非指针数据类型)。借鉴here 我们最常看到引用的地方是作为函数参数或返回值。
const with reference variable:
创建了一个临时对象,将const
引用绑定(bind)到它是合法的,但将它绑定(bind)到非const
引用是非法的。
就像:
const int& reference_to_const_int = int(20); //LEGAL
int& reference_to_const_int = int(20); //ILLEGAL
const
引用延长了临时对象的生命周期,这就是它起作用的原因。这只是语言的规则。 (我从 here 学到的)
关于c++ - const int& value = 12 和 const int value = 12 之间的区别;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12830619/
相关文章:
asp.net - BC30456 : CultureInfo is not a member of Globalization
c++ - `this == &x` 是确定指针 (this) 和引用 (x) 是否指向同一对象的正确方法吗?
ios - 我如何在 obj-c 的 block 中通过引用发送参数
c++ - 将 std::string 转换为 const char* 供 printf 消费
c++ - fatal error :iostream:Code::Blocks 中没有这样的文件或目录