我有重载 []
的类,当我尝试将值设置为数组时,我需要让它能够识别。我假设,我将不得不重载运算符 =
,但我不知道,整个东西会是什么样子。我的部分代码:
class Matrix {
public:
Matrix(int x, int y);
~Matrix(void);
Matrix& operator =(const Matrix &matrix); //ok...this is probably wrong...
class Proxy {
public:
Proxy(double* _array) : _array(_array) {
}
double &operator[](int index) const {
return _array[index];
}
private:
double* _array;
};
Proxy operator[](int index) const {
return Proxy(_arrayofarrays[index]);
}
Proxy operator[](int index) {
return Proxy(_arrayofarrays[index]);
}
int x, y;
double** _arrayofarrays;
};
所以当我尝试设置 Matrix matrix(3,3); 时,我只需要能够识别;矩阵[0][0]=1;
其他一切正常,所以我认为不需要粘贴整个代码
最佳答案
看起来你想要一些不可能直接实现的东西:operator[][].
您可以使用中间类来模拟此行为:
由于 Matrix 类通常索引为 [行][列],您可以
让第一个运算符方法返回相应的 Row 对象。
行类可以重载 operator[] 并返回相应的
元素。
Row& Matrix::operator[](int r);
double& Row::operator[](int c);
现在当您创建矩阵对象时,您可以按预期对其进行索引:
Matrix matrix(3,3);
matrix[0][0] = 1;
最后一行等同于调用:
matrix.operator[](0).operator[](0) = 1;
要检查越界索引,请存储矩阵大小:
Proxy operator[](int index) {
assert(index < num_rows);
return Proxy(_arrayofarrays[index]);
}
double &operator[](int index) const {
assert(index < num_cols);
return _array[index];
}
正如 Aldo 所建议的,Proxy 可以在其构造函数中传递数组长度值:
Proxy(double* _array, int _length) : _array(_array), num_cols(_length){
}
根据一般经验,如果您将原始数组传递给函数,您几乎总是希望同时传递该数组的长度。
关于c++ - 如何识别赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15771912/