我碰到一個代碼片斷來const引用可以分配一個int?
const int& reference_to_const_int = 20;
cout<<"\n reference_to_const_int = "<<reference_to_const_int<<endl;
此代碼編譯&與輸出執行: -
reference_to_const_int = 20
這東西對我來說陌生。據我所知,參考不佔用內存&他們是其他變量的別名。因此,我們不能說
int& reference_to_int = 30;
上述聲明不得編譯給錯誤: -
error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
究竟是在「const int的&」的情況下發生的是什麼?完整的解釋是需要的。
請幫助。
感謝
閱讀:http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ –
給它多一點想法,它似乎它*會*是合法的。如果不是這樣,你不可能在沒有更多變量的情況下設置它。 –
@GigaWatt:你在說什麼「它」?相信我,如果「它」*應該*是合法的,它*會*。 :) –