[問題] 重載下標符號 const 用途
參考這篇:https://goo.gl/33SyjS
我記得我之前有遇過這樣的狀況,缺少 const 函式不能編過
想不起來什麼是什麼情況了QuQ
// 重載下標符號
int & operator[](size_t idx){
return arr[idx];
}
// 重載下標符號 Const
const int & operator[](size_t idx) const{
return arr[idx];
}
什麼樣的情況下才會存取 const 版本的函式呢
照著文章做,也沒有執行到 const 版本的
測試代碼:http://ideone.com/fp5EBd
並沒有印出 **const**,是我誤會了什麼嗎?
怎麼樣才會印出 **const** 呢?
-------------------------------------------------------------
此外,因為要打2次也意味著修改要改兩處,所以就想說可不可以這樣
// 重載下標符號
int & operator[](size_t idx){
return arr[idx];
}
// 重載下標符號 Const
const int & operator[](size_t idx) const{
return (*this)[idx];
}
這樣只要改一處就好了,是可行的辦法嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.127.112.105
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1487584989.A.308.html
※ 編輯: hunandy14 (140.127.112.105), 02/20/2017 18:17:57
→
02/20 19:51, , 1F
02/20 19:51, 1F
→
02/20 19:52, , 2F
02/20 19:52, 2F
→
02/20 20:05, , 3F
02/20 20:05, 3F
→
02/20 20:12, , 4F
02/20 20:12, 4F
→
02/20 20:14, , 5F
02/20 20:14, 5F
→
02/20 20:14, , 6F
02/20 20:14, 6F
對耶~應該把主代碼寫在const內
不然const會呼叫const版本的永遠都跑不到主代碼
→
02/21 00:40, , 7F
02/21 00:40, 7F
了解~
→
02/21 00:44, , 8F
02/21 00:44, 8F
→
02/21 00:44, , 9F
02/21 00:44, 9F
→
02/21 00:45, , 10F
02/21 00:45, 10F
了解~
--- 感謝各位的答覆
※ 編輯: hunandy14 (140.127.112.105), 02/23/2017 11:57:35