c++ - 如何正确重载 '=' 运算符以使用重载 '[ ]' 运算符的数组?

标签 c++ arrays operator-overloading

我必须编写一个类 IntArray,它本质上是一个具有一些额外功能(未显示)的数组。我必须利用运算符重载将元素分配给 IntArray 对象中的整数数组。我的程序正确地检索了数组中的元素,但它无法分配数组中的元素。

#include <iostream>
using namespace std;

class IntArray{
    int *data;
    int SIZE;
    int startIndex;
    int endIndex;
public:
    IntArray(int endI);
    int operator[](int index);
    void operator=(int i);
};

IntArray::IntArray(int endI){
    SIZE = endI;
    data = new int[SIZE];
    endIndex = endI - 1;
    startIndex = 0;
}

int IntArray::operator[](int index){
    if(index > endIndex){
        cout << "Error: Index out of bounds" << endl;
        exit(0);
    }
    return data[index];
}

void IntArray::operator=(int i){
    data[0] = i;
}

我假设问题出在这个函数中:

void IntArray::operator=(int i);

这是我的主要方法:

int main(){
    IntArray a(0,1);
    cout << a[0] << endl; //works fine
    a[0] = 3; //does not work
}

我也不确定如何从 operator=(int i) 函数访问数组索引(main() 第 3 行的“0”)。感谢您的帮助!

最佳答案

a[0] = 3; //does not work

这不能编译与 operator= 重载无关。问题出在int operator[](int index);

您的 operator[] 重载返回一个 int,因此 a[0] 返回一个右值,您不能分配给一个右值。

解决方法是:

int& operator[](int index);

这样,operator[]返回一个引用(int&),它是一个左值,你可以给它赋值。

关于c++ - 如何正确重载 '=' 运算符以使用重载 '[ ]' 运算符的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517059/

相关文章:

c++ - 类指针和二元运算符 + 类指针类型的无效操作数

excel - Excel VBA 中的运算符重载

arrays - 在不精确的浮点运算中,乘法是否总是可交换的?

c++ - QT : cannot call member without object when I have a virtual function

arrays - 为什么 Excel.Range.Group 的 Periods 参数需要一个数组?

c - 不使用数组查找均值、中位数

c - 为什么下面程序中的 fgets 函数(请参阅详细信息)将字符串的长度解释为多一个字符?

c++ - 在 C++ 中,如何在没有 pop() 函数的情况下返回堆栈的第二个元素?

c++ - "expected ' ; zeromq 的 ' at the end of declaration list"错误

c++ - vector 对第一个元素的范围