说我有一个MyOwnArray
班,顾名思义,我想自己做一个
数组。我发现可以通过运算符重载来返回索引值。
#include <iostream>
using namespace std;
class MyOwnArray {
private:
int arr[3];
public:
MyOwnArray() {
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
}
int &operator[](int i) { // Also overload +, +=, etc?
return arr[i]; // and I'm only returning the value
// but it seems to modify when using "+="
// as demonstrated in main()
}
};
int main() {
MyOwnArray a; // my own array
cout << a[0]; // outputs "1".
a[0] += a[2]; // Not expecting this to work, but it does
cout << a[0]; // outputs "4"
return 0;
}
我期望cout << a[0]
输出值1
。
我没想到我会做类似a[0] += 1
的事情。操作符重载[]
是否也自动重载算术运算?
最重要的是:为什么我只返回以下内容时为什么a[0]
被修改了?
这个功能?
int &operator[](int i) { // Also overload +, +=, etc?
return arr[i]; // and I'm only returning the value
// but it seems to modify when using "+="
// as demonstrated in main()
}