如何识别赋值运算符?

时间:2013-04-02 18:45:14

标签: c++ operator-overloading

我有一个重载[]的类,当我尝试将值设置为数组时,我需要让它识别出来。我假设,我将不得不重载运算符=,但我不知道,整个东西怎么样。我的部分代码:

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); matrix[0][0]=1; 其他一切都很好,所以我认为不需要粘贴整个代码

2 个答案:

答案 0 :(得分:2)

看起来你想要一些不可能的东西:operator[][].

您可以使用中间类来模拟此行为:
由于Matrix类通常被索引为[rows] [columns],因此您可以使用 让第一个运算符方法返回相应的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){
 }

作为一般经验法则,如果您将原始数组传递给函数,您几乎总是希望传递该数组的长度。

答案 1 :(得分:1)

您的Proxy::operator[]重载正在返回double&。这个double&是最终由客户端代码分配的对象,你不能拦截它(至少不容易)。您可能需要做的是检查index重载中的operator[]参数,并在那里抛出自己的异常,而不是将该索引传递给内部数组。