[問題] const pointer

看板C_and_CPP (C/C++)作者 (做遊戲的心)時間15年前 (2010/11/02 22:39), 編輯推噓1(106)
留言7則, 4人參與, 最新討論串1/1
class Student { public: void Read(){} }; const Student *pStu1 = new Student; Student const *pStu2 = new Student; pStu1->Read();// error pStu2->Read();// error 以上是程式碼 小弟目前知道pStu1與pStu2的宣告其實是一樣 但不了解為何一樣 其二 為什麼無法呼叫其成員函式Read()? 錯誤訊息: 無法將 'this' 指標從 'const Student' 轉換成 'Student &' 煩請各位板友提點一下~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 112.104.97.176 ※ 編輯: NIKE74731 來自: 112.104.97.176 (11/02 22:40)

11/02 22:51, , 1F
為什麼Student類別要用int指標去指呢?
11/02 22:51, 1F
※ 編輯: NIKE74731 來自: 112.104.97.176 (11/02 22:55)

11/02 22:55, , 2F
打錯了.... 不好意思
11/02 22:55, 2F

11/02 22:57, , 3F
沒有 member ?
11/02 22:57, 3F

11/02 22:58, , 4F
((Student*)pStu1)->Read(); 這樣行不行??
11/02 22:58, 4F

11/02 22:59, , 5F
Read() const <= 加const變const member function就可以了
11/02 22:59, 5F

11/02 22:59, , 6F
const的物件或指標只能呼叫是const的 member function.
11/02 22:59, 6F

11/02 23:01, , 7F
喔~~謝謝layan大!
11/02 23:01, 7F
文章代碼(AID): #1Cq2AZiF (C_and_CPP)
文章代碼(AID): #1Cq2AZiF (C_and_CPP)