0

我对以下内容有疑问。我实现矩阵。有一个用于整个矩阵的类和一个用于一行矩阵的类。我创建了行,以便可以访问像矩阵 [a] [b] 这样的成员。但问题在于抛出异常,其格式必须类似于“无效索引 [e][f]”。我会在矩阵重载 [] 中使用 try-catch 并从行重载 [] 中抛出整数异常,但它不能解决第一个索引正常而第二个索引错误的情况。

//Matrix overload
Row& operator [] (unsigned inx) {
return *rows[inx];
}

//Row overload
double& operator [] (unsigned inx) 
{
return items[inx];
}
4

1 回答 1

1

异常必须采用类似“无效索引 [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];
}
于 2013-03-26T21:15:00.700 回答