重载2D数组操作符并抛出异常

Overloading 2D array operator and throwing exception

本文关键字:抛出异常 操作符 数组 2D 重载      更新时间:2023-10-16

我一直在考虑这个问题,但没有想到任何有用的东西。我有两个类表示的矩阵:

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;

,所以它可以抛出关于两个索引的信息异常,而不管其中哪个是错误的。我也想让它尽可能的简单。你能想到什么吗?

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

通常使用operator()实现两个参数的矩阵访问,而不是使用带有辅助类的operator[]。所以不用matrix[i][j],用matrix(i, j)。这使您的问题更容易解决,还可能提高性能。参见"为什么我的Matrix类的接口不能看起来像数组的数组?"了解更多信息。

最终我做到了

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