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?
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.
来源:https://stackoverflow.com/questions/37051502/c-operator-overloading-for-lvalue-and-rvalue