[問題] const reference

看板C_and_CPP作者 (Ar藤)時間13年前 (2012/01/05 15:47), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串2/3 (看更多)
因為程式碼比較短也直接貼在下方(http://codepad.org/o7M1WcFG) 程式碼輸出為 500 0 0 500 500 500 123 123 123 請問為什麼 int const & x 以 500 初始化後 此值會被洗掉 而 static int const &k = 123 這個值不會被洗掉 這背後的機制是什麼呢? =========================================================== #include <iostream> #include <cstdio> using namespace std; class foo { public: int const & x; foo():x(500) { } }; void test2() { static int const &k = 123; cout<<k<<endl; } int main() { foo a; cout<<a.x<<endl; cout<<a.x<<endl; cout<<a.x<<endl; const int &cir = 500; cout<<cir<<endl; cout<<cir<<endl; cout<<cir<<endl; test2(); test2(); test2(); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.135.140.149

01/06 00:02, , 1F
為什麼宣告變數都要加上&?
01/06 00:02, 1F

01/06 10:04, , 2F
我在試驗const &的行為
01/06 10:04, 2F
文章代碼(AID): #1F1SOa-v (C_and_CPP)
討論串 (同標題文章)
以下文章回應了本文
問題
3
3
完整討論串 (本文為第 2 之 3 篇):
問題
3
3
問題
0
2
問題
2
4
文章代碼(AID): #1F1SOa-v (C_and_CPP)