5

我有一个矩阵类,它使用 [][] 来访问元素。当一个(或两个)索引超出范围时,我必须抛出 CIndexException。这是一个以“无效索引 [a][b]”格式存储文本的类,其中 a 和 b 是数字。

这是我当前对 CIndexException 类的实现

class CIndexException
{
    string text;
public:
    CIndexException (int a, int b)
    {
        ostringstream oss;
        oss << "Invalid index [";
        oss << a;
        oss << "][";
        oss << b;
        oss < "]";

        text = oss.str();
     }

     string get() const
     {
         return text;
     }
};

矩阵表示为一个二维数组,它在构造函数中初始化:

CMatrix(int r, int c)
{
    colls = c;
    rows = r;
    mat = new double * [rows];

    for (int i = 0; i < rows; i++)
    {
        mat[i] = new double [colls];
        for (int j = 0; j < colls; j++)
            mat[i][j] = 0;
    }
}

为了获得单个元素,我重载了 [] 运算符,如下所示:

double * operator[] (int x) const
{
    return mat[x];
}

当我键入 a[2][3] 时,此函数解析第一个 [],返回指向数组的指针,然后像往常一样解析第二个 []。

我可以轻松检查第一个索引是否超出范围,但我无法检查第二个索引。我想创建第二个类 MatrixRow,它代表一行矩阵。然后我会有 MatrixRows 数组。为了使 [][] 工作,这两个类都将重载 operator[]。这样我就可以检查两个索引,但我不知道如何将它们“加入”到一个异常中。使用此设计时如何报告异常对象中的两个索引?

4

2 回答 2

3

使用您的MatrixRow解决方案,但将行的索引MatrixRow作为构造函数参数传递给每个。可以保存该MatrixRow数字,并在它生成的任何异常消息中使用它。

于 2013-03-24T14:44:00.590 回答
1

Use operator()() instead of operator[](). See this link. All what you need this link considers.

于 2013-03-24T14:52:57.547 回答