C++ Operator Overloading [ ] for lvalue and rvalue

2020-07-25 09:42发布

I made a class Array which holds an integer array. From the main function, I'm trying to get an element of the array in Array using [ ] as we do for arrays declared in main. I overloaded the operator [ ] as in the following code; the first function returns an lvalue and the second an rvalue (Constructors and other member functions are not shown.)

#include <iostream>
using namespace std;

class Array {
public:
   int& operator[] (const int index)
   {
      return a[index];
   }
   int operator[] (const int index) const
   {
      return a[index];
   }

private:
   int* a;
}

However, when I try to call those two functions from main, only the first function is accessed even when the variable is not used as an lvalue. I can't see the point of creating a separate function for an rvalue if everything can be taken care of just by using the lvalue function.

The following code is the main function I used (Operator << is appropriately overloaded.):

#include "array.h"
#include <iostream>
using namespace std;

int main() {
   Array array;
   array[3] = 5;                // lvalue function called
   cout << array[3] << endl;    // lvalue function called
   array[4] = array[3]          // lvalue function called for both
}

Is there any way I can call the rvalue function? Is it also necessary to define functions for both lvalue and rvalue?

1条回答
放荡不羁爱自由
2楼-- · 2020-07-25 10:42

The second function is a const member function and it will be called if you have a const instance:

const Array array;
cout << array[3] << endl;  // rvalue function called

It isn't conventional to call these "lvalue" and "rvalue" functions. And you could define the const one to return a const reference if you want.

查看更多
登录 后发表回答