views:

99

answers:

2

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 accomplish 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?

+12  A: 

You don't overload the = operator. You return a reference.

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

Make sure to provide a const version as well:

const int& operator[](int p_index) const
{
   return a[p_index];
}
KennyTM
+1. In addition, you may want to overload on const: `int operator[](int p_index) const`
Fred Larson
David Rodríguez - dribeas
@David, that's probably not a good idea if you want to take its address. `foo = ` is broken with `a` being a const `A`.
Johannes Schaub - litb
+4  A: 

Make it return a reference:

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

Note that you will also want a const version, which does return a value:

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