它必須用類(lèi)的成員函數(shù)來(lái)實(shí)現(xiàn),而不能用友元函數(shù) 按位置索引快速的訪問(wèn)容器類(lèi)的單個(gè)元素,容器如string,數(shù)組,vector等 重載下標(biāo)運(yùn)算符[]設(shè)計(jì)方案 一般要實(shí)現(xiàn)兩個(gè)[]運(yùn)算符,一個(gè)用于訪問(wèn)加上const,一個(gè)用于修改不加const. 定義[] class demo { public: int& operator[](const size_t); //用于修改 const int& operator[](const size_t)const; private: vector<int> data; }; 實(shí)現(xiàn)[] int& demo::operator[](const size_t index) { return data[index];} const int& demo::operator[](const size_t index)const { return data[index];}
|