C ++ overload [] left and right

I'm trying to figure out how I can overload [] on both left and right to function as set and retrieve for a custom string class I'm working on. eg:

char x= objAr[1]; //get
objAr[2]='a'; //set

      

The string class basically looks like this:

class String {
private:
    char* data;
    unsigned int dataSize;
public:
    String();
    String(char);
    String(char*);
    String(String&);
    ~String();
    char* getData();
    int getSize();
};

      

+3


source to share


1 answer


If you always have data to back up, you can return the link:

char& String::operator[] (size_t idx)
{ return data[idx]; }

char String::operator[] (size_t idx) const
{ return data[idx]; }

      

In your case, that should be enough. However, if it was not for some reason (for example, if the data is not always of the correct type), you can also return a 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}; }
};

      

It will also allow you to do things like copy-write implicit communication.

+7


source







All Articles