c++ - 二维索引异常

标签 c++ exception matrix

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

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

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

最佳答案

exception must be in format like "Invalid index [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];
}

关于c++ - 二维索引异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15647462/

相关文章:

c++ - 新构造的对象作为默认模板函数参数

C++ 作业函数错误

c# - 异常与返回码 : do we lose something (while gaining something else)?

algorithm - 使用 n 个标签标记网格,其中每个标签都与其他每个标签相邻

python - 在Python中将矩阵转换为图像

c++ - 使用 C/C++ 实现德摩根定律

c++ - 最大化 tensorflow 多 GPU 性能

java - 是否有任何理由将异常的原因设置为自身?

java - 使用 spring DataAccessExceptions 代替 JPA PersistenceExceptions 有什么优势吗?

c - c编程中具有函数递归的nxn矩阵的行列式