我有一个矩阵类,它使用 [][] 来访问元素。当一个(或两个)索引超出范围时,我必须抛出 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;
}
};
矩阵表示为 double 的二维数组,它在构造函数中初始化:
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[]。这样我就可以检查两个索引,但我不知道如何将它们“加入”到一个异常中。使用此设计时如何在异常对象中报告两个索引?
最佳答案
使用您的 MatrixRow
解决方案,但将行的索引作为构造函数参数传递给每个 MatrixRow
。 MatrixRow
可以保存该数字,并在它生成的任何异常消息中使用它。
关于c++ - 数组越界时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15599753/