Work with the operator [] and operator =

Given a simple class that overloads the [] operator:

class A
{
  public:
    int operator[](int p_index)
    {
       return a[p_index];
    }

  private:
    int a[5];
};

I would like to do the following:

void main()
{
   A Aobject;

   Aobject[0] = 1;  // Problem here
}

How can I overload the assignment operator '=' in this case to work with the operator [] '?

+3
source share
3 answers

You do not overload the operator =. You are returning the link.

int& operator[](int p_index)
{
   return a[p_index];
}

Be sure to specify the version const:

const int& operator[](int p_index) const
{
   return a[p_index];
}
+16
source

Set link:

int & operator[](int p_index)
{
   return a[p_index];
}

Note that you will also need a const version that returns a value:

int operator[](int p_index) const
{
   return a[p_index];
}
+5
source

, , vaiable a.

int, .

" C2106: '=': l-value", .

, , .

Please change the return type of the function [] overload to a link or pointer, which will work fine.

0
source

Source: https://habr.com/ru/post/1744016/


All Articles