[問題] const int *& 給值的問題
開發平台(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):
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.135.48.199
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1475230865.A.28A.html
→
09/30 18:24, , 1F
09/30 18:24, 1F
這邊的指標指到 NULL 啊
※ 編輯: seanooxox (220.135.48.199), 09/30/2016 18:33:47
推
09/30 18:48, , 2F
09/30 18:48, 2F
→
09/30 18:48, , 3F
09/30 18:48, 3F
→
09/30 19:06, , 4F
09/30 19:06, 4F
→
09/30 20:17, , 5F
09/30 20:17, 5F
→
09/30 20:17, , 6F
09/30 20:17, 6F
→
09/30 20:36, , 7F
09/30 20:36, 7F
→
09/30 20:57, , 8F
09/30 20:57, 8F
→
09/30 20:57, , 9F
09/30 20:57, 9F
→
09/30 20:57, , 10F
09/30 20:57, 10F
→
09/30 20:57, , 11F
09/30 20:57, 11F
→
09/30 21:46, , 12F
09/30 21:46, 12F
→
09/30 21:48, , 13F
09/30 21:48, 13F
→
09/30 22:27, , 14F
09/30 22:27, 14F
→
09/30 22:28, , 15F
09/30 22:28, 15F
→
09/30 22:29, , 16F
09/30 22:29, 16F
→
09/30 22:35, , 17F
09/30 22:35, 17F
→
09/30 22:37, , 18F
09/30 22:37, 18F
→
09/30 22:38, , 19F
09/30 22:38, 19F
推
10/01 03:05, , 20F
10/01 03:05, 20F
→
10/01 03:05, , 21F
10/01 03:05, 21F
→
10/01 08:20, , 22F
10/01 08:20, 22F
→
10/01 08:21, , 23F
10/01 08:21, 23F
→
10/01 08:22, , 24F
10/01 08:22, 24F
→
10/01 08:27, , 25F
10/01 08:27, 25F
→
10/01 08:27, , 26F
10/01 08:27, 26F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章