【问题标题】:How do I properly overload the '=' operator to work with an array that is overloading the '[ ]' operator?如何正确重载“=”运算符以使用重载“[]”运算符的数组?
【发布时间】:2016-07-22 02:02:19
【问题描述】:

我必须编写一个类,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”)。感谢您的帮助!

【问题讨论】:

  • return data[index - startIndex]; 嗯???
  • 我认为您不想在数组类中使用 operator=。见stackoverflow.com/questions/3581981/…
  • 一般情况下也可以通过return (*this)返回IntArray &amp;。 “无法分配”是指崩溃,还是说未能这样做?
  • @πάντα ῥεῖ 分配要求 IntArray 对象具有负索引。 return data[index - startIndex] 允许我将索引从负数转换为它们在正常数组中的位置。你的问题让我意识到我没有提供可以解释这一点的代码。
  • @M4rc 我的意思是崩溃。

标签: c++ arrays operator-overloading


【解决方案1】:

a[0] = 3; //不起作用

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

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

解决办法是:

int&amp; operator[](int index);

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

【讨论】:

  • 你才是真正的mvp
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 2012-03-14
  • 2020-01-03
  • 1970-01-01
相关资源
最近更新 更多