推 seansylin:了解,謝謝! 04/22 19:18
※ 引述《seansylin (sylin)》之銘言:
: 我可以
: int a=1024;
: int *pt=&a;
: int *&ref=pt;
: 但不行
: int a=1024;
: int *&ref=&a;
因為reference維護的是某個物件的"address"
而上面那行&a 會有個隱式型別轉換
你的compiler 會產生個暫時物件
比如說會把你 int *&ref=&a 的 code轉成
int *tempPtr = &a;
int *&ref = tempPtr;
可是一旦你改變ref的話 影響的將是 tempPtr 而不是 a
所以C++ 並不允許non-const reference代表那些需要暫時替代品的物件或數值
而const reference 可以 因為你沒法改變
所以你下面的程式ok
: 但是可以
: int a=1024;
: int * const &ref=&a;
: 為什麼呢?
: 那麼
: int a=1024;
: int *pt=&a;
: int * const &ref=pt;
: 又是什麼意思呢?
: 謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.163.142.103
※ 編輯: SHBK 來自: 218.163.142.103 (04/22 18:11)