【发布时间】: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 &。 “无法分配”是指崩溃,还是说未能这样做? -
@πάντα ῥεῖ 分配要求 IntArray 对象具有负索引。 return data[index - startIndex] 允许我将索引从负数转换为它们在正常数组中的位置。你的问题让我意识到我没有提供可以解释这一点的代码。
-
@M4rc 我的意思是崩溃。
标签: c++ arrays operator-overloading