[問題] operator[] 如何進行overloading

看板C_and_CPP (C/C++)作者 (電費不繳)時間10年前 (2015/09/17 15:56), 編輯推噓0(007)
留言7則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) clang++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 想請問一下,[]運算子如何進行overloading?一般來說[]運算子不是會被當成陣列存取的位址嗎? 這樣為什麼cpp reference寫說可以使用[]來進行多載? 以下是我的code #include<iostream> using namespace std; class A{ public: A(string x){ text=x; } char& operator[](size_t position){ return text[position]; } void get(){ cout<<text[1]<<endl; } private: string text; }; int main(){ string x="Hello World"; A *p=new A(x); char &y=p[0]; cout<<p[0]<<endl; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.123.101.71 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1442476566.A.B0F.html

09/17 16:30, , 1F
不是陣列或指標的東西就可以給他其他意義啊
09/17 16:30, 1F

09/17 16:34, , 2F
map就不是陣列啦 要看[]不是[]
09/17 16:34, 2F

09/17 21:30, , 3F
謝謝兩位大大回覆,我後來令成靜態的物件就可以了
09/17 21:30, 3F

09/17 21:31, , 4F
請問一下動態記憶體的物件沒辦法存取[]運算子嗎?
09/17 21:31, 4F

09/17 21:35, , 5F
(*p)[0]
09/17 21:35, 5F

09/17 22:20, , 6F
p -> operator[] (0) ; (*p)[0]
09/17 22:20, 6F

09/18 02:51, , 7F
謝謝! 獲益良多
09/18 02:51, 7F
文章代碼(AID): #1L-d8MiF (C_and_CPP)
文章代碼(AID): #1L-d8MiF (C_and_CPP)