Re: [问题] const int *& 给值的问题

楼主: hunandy14 (Charlott.HonG)   2016-10-01 13:45:16
根据其他人的回复,推出的答案
自己打了代码做实验
你也可以直接从里面修改
可能会比较快弄懂~
程式码:https://goo.gl/bYgnhJ
int* p1 = nullptr;
int* & a = p1; /* 为什么 int 前不能加 const */
const int* & a = p1;
int num=1;
假设你设定了 a=&num1
先印出来 *a=> 印出 1
然后你对 *p1 做修改 *p1=2;
我们在印一次 *a=> 印出2
这违反const的定义不能被修改
可以推出,我们连上一层
也一起限制就没事了~
const int* p1=nullptr;
const int* & a = p1;
※ 引述《seanooxox (0n羊)》之铭言:
: 开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
: G++, Linux
: 额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
: 问题(Question):
: 请问各位大大,为什么这段程式码 compile 不过?
: 小弟跪求解释
: int main() {
: int *b = 0;
: const int *& n = b;
: }
: 错误讯息:
: error: invalid initialization of non-const reference of type 'const int*&' from an rvalue of type 'const int*'
: 我有找到这篇说是因为type-safe 的关系:
: http://stackoverflow.com/a/11514730
: 但是如果把程式改成这样,也没有type-safe,可是却可以成功compile
: int a = 0;
: int *b = &a;
: const int & n = *b;
: cout << n << endl; // n = 0
: *b = 3;
: cout << n << endl; // n = 3
: 又看到了这篇的回答:http://stackoverflow.com/a/31412466
: 但是却也看不太懂他的回答是什么意思,为什么它会回传rvalue?
: 还有,为什么宣告成 const int * const & n = b 就可以compile 过?
: 感谢各位大大!
: 程式码(Code):(请善用置底文网页, 记得排版)
: http://ideone.com/W5kqRr
: 补充说明(Supplement):

Links booklink

Contact Us: admin [ a t ] ucptt.com