重载2D数组运算符并抛出异常

时间:2013-04-05 22:35:05

标签: c++ matrix operator-overloading multidimensional-array square-bracket

我一直在考虑这个问题,并没有提出任何有用的东西。我有两个类代表的矩阵:

class CMatrix {
public:
    CMatrixRow * matrix;
    int height, width;
    CMatrix(const int &height, const int &width);
    CMatrix(const CMatrix &other);
    ~CMatrix();
    CMatrixRow operator [] (const int &index) const; 
    ...
}

class CMatrixRow {
public:
    int width;
    CMatrixRow(const int &width);
    CMatrixRow(const CMatrixRow &other);
    ~CMatrixRow();
    double operator [] (const int index) const;
    void operator =(const CMatrixRow &other);
private:
    double * row;

};

其中CMatrix是矩阵行(CMatrixRow)的容器。 当有人试图访问其边界之外的矩阵时,或者换句话说,其中一个使用的索引大于矩阵的大小时,我需要抛出异常。问题是,我需要以某种方式将第一个索引传递给方法

double operator [] (const int index) const;

所以它可以抛出有关两个索引的信息的异常,无论它们中哪一个是错误的。我也希望尽可能简单。你能想到什么吗?

2 个答案:

答案 0 :(得分:1)

您的CMatrixRow需要能够找到容器中的哪一行。一种简单的方法是为CMatrixRow的构造函数提供一个额外的参数,该参数是它的行索引,然后它可以在创建之后保留。但是,这是一种冗余形式,如果您开始移动CMatrixRow,可能会导致问题。

通常使用operator()实现矩阵访问,使用两个参数,而不是使用辅助类operator[]。因此,您需要执行matrix[i][j]而不是matrix(i, j)。这使您的问题更容易,也可能导致性能提升。有关详细信息,请参阅"Why shouldn't my Matrix class's interface look like an array-of-array?"

答案 1 :(得分:0)

最终我设法像这样做了

class CMatrix {
public:
    double ** matrix;
    int height, width, throwFirstIndex;

    class Proxy {
    public:
        Proxy(double * array, const int width, const int rowIndex, bool fail = false);
        double & operator [] (const int &index) const;
    private:
        double * row;
        int width, rowIndex;
        bool fail;
    };

    CMatrix(const int &height, const int &width);
    CMatrix(const CMatrix &other);
    ~CMatrix();
    Proxy operator [] (const int &index) const;
    ...
};

我基本上复制了这个:Operator[][] overload