C++ Operator Overloading [ ] for lvalue and rvalue

限于喜欢 提交于 2019-12-06 12:07:16

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!