左值和右值的C ++运算符重载[] [英] C++ Operator Overloading [ ] for lvalue and rvalue
问题描述
我制作了一个包含整数数组的Array类.从main函数中,我试图像使用main中声明的数组那样使用[]获取Array中的数组元素.我在下面的代码中重载了运算符[];第一个函数返回一个左值,第二个函数返回一个右值(未显示构造函数和其他成员函数.)
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;
}
但是,当我尝试从main调用这两个函数时,即使未将变量用作左值,也只能访问第一个函数.如果可以仅通过使用lvalue函数来处理所有事情,那么我看不到为rvalue创建单独的函数的意义.
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?
推荐答案
第二个函数是const member function
,如果您有const
实例,它将被调用:
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
调用这些"lvalue"和"rvalue"函数并不常见.如果需要,可以定义一个const来返回const引用.
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.
这篇关于左值和右值的C ++运算符重载[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!