開發平台(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):
作者:
pttworld (批踢踢世界)
2016-09-30 18:24:00「指」標要指得到東西,什麼被指到。
int* const & n = b;就是const修飾到什麼的問題
作者:
pttworld (批踢踢世界)
2016-09-30 19:06:00const int *b = 0;
0 在這邊就是NULL的意思啊,而且就算換成其他東西也會有一樣的錯誤
作者:
pttworld (批踢踢世界)
2016-09-30 20:36:00可以嘗試全篇翻英丟上,語法解法已給。問題本身不明確。
先感謝您的回覆,可能是我表達的不清楚。那我換個方式問問題好了,在我程式碼中紅色字的那一行,如果拿掉const的修飾,就會變得可以compile,我想知道這個跟rvalue有什麼關聯
作者:
pttworld (批踢踢世界)
2016-09-30 21:46:00lr以assignment hand side判定。只是編譯器認為指定失敗,不能,不過而已。
作者:
klsdf (靜雨澪)
2016-09-30 22:27:00就我的理解是 (const int) * & 你用一個型態指向const int的指標去ref一個int *本來就會跟你說型態錯誤你用(const int) (* const) & 可以過是因為你的pointer是const不可更改 ref的語意有被推導出來 等其他強者解釋 QQ就是const int *&是lvalue ref 他應該是a等效為b但a是const int, 你*b改了值 *a也會跟著改就語意矛盾
作者: ralts (拉魯拉絲) 2016-10-01 03:05:00
b 會先 implicit 轉型成 const int* 的 rvalue, 而錯誤在 rvalue 只能有 const reference.
作者:
g0010726 (Kevin)
2016-10-01 08:20:00一開始的code紅色行給你編譯過的話 你就可以做:const int cint; n = &cint;*b = 100; //改到cint惹 爆炸也就是 想在type的某level加上const,得要一路往上每個level加const。 除了top level 可以不用管