看板 C_and_CPP 關於我們 聯絡資訊
開發平台(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
azureblaze: 不是陣列或指標的東西就可以給他其他意義啊 09/17 16:30
x000032001: map就不是陣列啦 要看[]不是[] 09/17 16:34
ArcherState: 謝謝兩位大大回覆,我後來令成靜態的物件就可以了 09/17 21:30
ArcherState: 請問一下動態記憶體的物件沒辦法存取[]運算子嗎? 09/17 21:31
suhorng: (*p)[0] 09/17 21:35
EdisonX: p -> operator[] (0) ; (*p)[0] 09/17 22:20
ArcherState: 謝謝! 獲益良多 09/18 02:51