看板 C_and_CPP 關於我們 聯絡資訊
參考這篇: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
ilikekotomi: 用到const需要物件也是const 02/20 19:51
ilikekotomi: 把line35 改成const Arr a(5);就可以了 02/20 19:52
ilikekotomi: 打兩次的地方可以參考Effective C++的條款三 02/20 20:05
ilikekotomi: http://ideone.com/ZyqPgc 書上做法是這樣 02/20 20:12
ilikekotomi: 目前你的方法會因為進到const版本時 *this也是const 02/20 20:14
ilikekotomi: 所以一直呼叫自己造成runtime error 02/20 20:14
對耶~應該把主代碼寫在const內 不然const會呼叫const版本的永遠都跑不到主代碼
bluesoul: 用const物件呼叫就可以了 02/21 00:40
了解~
LPH66: 如果有沒有 const 沒差的話寫 const 版就足夠了 02/21 00:44
LPH66: 有差的話用個 const_cast 把一種轉成另一種即可 02/21 00:44
LPH66: (即是四樓程式碼的做法) 02/21 00:45
了解~ --- 感謝各位的答覆 ※ 編輯: hunandy14 (140.127.112.105), 02/23/2017 11:57:35