开发者

Working with operator[] and operator=

开发者 https://www.devze.com 2022-12-29 07:03 出处:网络
Given a simple class that overloads the \'[ ]\' operator: class A { public: int operator[](int p_index) { return a[p_index];

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 accomp开发者_如何学编程lish 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?


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];
}


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];
}


The problem here is you are returning the value which is contained in vaiable a.

In main you are trying to assign int variable which is not available.

You would have seen compilation error "error C2106: '=' : left operand must be l-value" like this.

Means the value cannot be assigned to a variable which is not available.

Please change return type of operator [] overloading function into reference or pointer it will work fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消