异常必须采用类似“无效索引 [e][f]”的格式
这比听起来更棘手!
如果[f]
无效,Matrix::operator[]( e )
则已经完成。该参数不再可用。
因此,您需要Row
在某个时候将此信息传递给相关问题。这是一种方法。
// (Member variable "int Row::index" is added...)
//Matrix overload
Row& operator [] (unsigned inx) {
rows[inx]->setRowIndex(inx);
return *rows[inx];
}
//Row overload
double& operator [] (unsigned inx)
{
// Now you can throw information about both inx and the stored row index
return items[inx];
}
如果[e]
无效,Row::operator[]( f )
则尚未调用。这是一个未知的值。
这意味着即使[e]
是无效的,它也必须返回一些operator[]
在抛出之前仍然可以调用的东西。
// (Member variable "bool Row::isInvalid" is added...)
//Matrix overload
Row& operator [] (unsigned inx) {
Row *result;
if ( inx is invalid )
{
// Don't throw yet!
static Row dummy;
dummy.setInvalid();
result = &dummy;
}
else
{
result = rows[inx];
}
result->setRowIndex(inx);
return *result;
}
//Row overload
double& operator [] (unsigned inx)
{
// If this->isInvalid is true, the first index was bad.
// If inx is invalid, the second index was bad.
// Either way, we have both indices now and may throw!
return items[inx];
}