[問題] const reference
因為程式碼比較短也直接貼在下方(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
01/06 10:04, 2F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 2 之 3 篇):