由“不可寻址的值必须const引用”而起(C++)
还是一步一步来么:
1. “const int a = 2;”等价于“int const a = 2;”。
2. “不可寻址的值必须const引用”,《C++ Primer》有说,(由于临时变量的存在,)“不允许非const 引用指向需要临时对象的对象或值,一般来说这,比‘允许定义这样的引用,但实际上不会生效’的方案要好得多”。
3. 于是,
4. 地址值也是不可寻址的值。所以,![](https://www.cnblogs.com/Images/dot.gif)
int* const & ref3 = &a; // OK.
// 注意“int* const & ref3”不等价于“const int* & ref3”,
// 因为“int* const”不等价于“const int*”,
// 注意跟“const int”等价于“int const” 的区别。
5. 于是,用const对象的地址来初始化一个指向指针的引用:![](https://www.cnblogs.com/Images/dot.gif)
![](https://www.cnblogs.com/Images/dot.gif)
const int b = 23;
const int* p = &b;
const int* & ref4 = p;
const int* const & ref5 = &b;// OK.
这样子,const引用该了了么。
1. “const int a = 2;”等价于“int const a = 2;”。
2. “不可寻址的值必须const引用”,《C++ Primer》有说,(由于临时变量的存在,)“不允许非const 引用指向需要临时对象的对象或值,一般来说这,比‘允许定义这样的引用,但实际上不会生效’的方案要好得多”。
3. 于是,
int a = 2;
int & ref1 = a; // OK.有过渡变量。
int const & ref2 = 2; // OK.编译器产生临时变量,直接引用。
int & ref1 = a; // OK.有过渡变量。
int const & ref2 = 2; // OK.编译器产生临时变量,直接引用。
4. 地址值也是不可寻址的值。所以,
![](https://www.cnblogs.com/Images/dot.gif)
int* const & ref3 = &a; // OK.
// 注意“int* const & ref3”不等价于“const int* & ref3”,
// 因为“int* const”不等价于“const int*”,
// 注意跟“const int”等价于“int const” 的区别。
5. 于是,用const对象的地址来初始化一个指向指针的引用:
![](https://www.cnblogs.com/Images/dot.gif)
![](https://www.cnblogs.com/Images/dot.gif)
const int b = 23;
const int* p = &b;
const int* & ref4 = p;
const int* const & ref5 = &b;// OK.
这样子,const引用该了了么。