例外必須是像格式 「無效的指數[E] [F]」
這是棘手比它的聲音!
如果[f]
無效,Matrix::operator[](e)
已經完成。該參數不再可用。
因此,您需要將此信息傳遞給有問題的。這是一種方法。
// (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];
}
你不能重載只是返回類型。重載需要一個不同的簽名。 – Freddy 2013-03-26 21:13:16
讓'Row'對象跟蹤它所關聯的索引。 – 2013-03-26 21:13:28
@Freddy它們在不同的類中實現。是的,這個問題並不完全清楚。 – 2013-03-26 21:13:33