string - C++ Overloading [] from left and right -
i'm trying think how can overload [] both left , right function set , custom string class i'm working on. example:
char x= objar[1]; //get objar[2]='a'; //set the string class looks this:
class string { private: char* data; unsigned int datasize; public: string(); string(char); string(char*); string(string&); ~string(); char* getdata(); int getsize(); };
if have data up, can return reference:
char& string::operator[] (size_t idx) { return data[idx]; } char string::operator[] (size_t idx) const { return data[idx]; } in case, should sufficient. however, if not option whatever reason (e.g. if data not of proper type), return proxy object:
class string { void setchar(size_t idx, char c); char getchar(size_t idx); class charproxy { size_t idx; string *str; public: operator char() const { return str->getchar(idx); } void operator= (char c) { str->setchar(idx, c); } }; public: charproxy operator[] (size_t idx) { return charproxy{idx, this}; } const charproxy operator[] (size_t idx) const { return charproxy{idx, this}; } }; this enable things implicit data sharing copy-on-write.
Comments
Post a Comment