如何正确重载"="运算符以使用重载"[ ]"运算符的数组?
How do I properly overload the '=' operator to work with an array that is overloading the '[ ]' operator?
我必须编写一个类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
}
我也不知道如何从运算符=(int I)函数访问数组索引(main()第3行的"0")。谢谢你的帮助!
a[0]=3//不起作用
这与operator=
重载无关。问题出在int operator[](int index);
operator[]
重载返回一个int
,因此a[0]
返回一个右值,并且不能分配给右值。
解决方案是:
int& operator[](int index);
通过这种方式,operator[]
返回一个引用(int&
),它是一个左值,您可以为它赋值。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板