重载2D数组操作符并抛出异常
Overloading 2D array operator and throwing exception
我一直在考虑这个问题,但没有想到任何有用的东西。我有两个类表示的矩阵:
class CMatrix {
public:
CMatrixRow * matrix;
int height, width;
CMatrix(const int &height, const int &width);
CMatrix(const CMatrix &other);
~CMatrix();
CMatrixRow operator [] (const int &index) const;
...
}
class CMatrixRow {
public:
int width;
CMatrixRow(const int &width);
CMatrixRow(const CMatrixRow &other);
~CMatrixRow();
double operator [] (const int index) const;
void operator =(const CMatrixRow &other);
private:
double * row;
};
其中CMatrix是矩阵(CMatrixRow)的行容器。当有人试图访问矩阵的边界之外,或者换句话说,其中一个使用的索引大于矩阵的大小时,我需要抛出一个异常。问题是,我需要将第一个索引传递给
方法double operator [] (const int index) const;
,所以它可以抛出关于两个索引的信息异常,而不管其中哪个是错误的。我也想让它尽可能的简单。你能想到什么吗?
您的CMatrixRow
需要能够找出它在您的容器中的哪一行。一种简单的方法是为CMatrixRow
的构造函数提供一个额外的参数,作为它的行索引,然后它可以在创建后保留该参数。然而,这是一种冗余,如果你开始移动CMatrixRow
,可能会导致问题。
通常使用operator()
实现两个参数的矩阵访问,而不是使用带有辅助类的operator[]
。所以不用matrix[i][j]
,用matrix(i, j)
。这使您的问题更容易解决,还可能提高性能。参见"为什么我的Matrix类的接口不能看起来像数组的数组?"了解更多信息。
最终我做到了
class CMatrix {
public:
double ** matrix;
int height, width, throwFirstIndex;
class Proxy {
public:
Proxy(double * array, const int width, const int rowIndex, bool fail = false);
double & operator [] (const int &index) const;
private:
double * row;
int width, rowIndex;
bool fail;
};
CMatrix(const int &height, const int &width);
CMatrix(const CMatrix &other);
~CMatrix();
Proxy operator [] (const int &index) const;
...
};
Operator[][] overload
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- 函数如何通知用户它基于函数原型抛出异常?
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- VisualStudios 会抛出异常,而代码块不会 [C++]
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- ZMQ::send() 抛出异常并终止 QNX 进程.为什么以及如何从中恢复?
- new(std::nothrow) int[n] 抛出异常
- 为什么g_object_set抛出异常(vcruntime140.dll)?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- C++子线程抛出异常
- 我们应该在抛出异常之前取消分配内存吗
- 有没有一种方法可以让OpenCLC++绑定为所有错误抛出异常
- 为什么访问模板化变体作为返回值抛出异常
- 如何实现,错误分配中止而不是抛出异常
- std::p riority_queue::p op什么时候会抛出异常
- 在0x5914F3BE抛出异常(基于.dll)
- std::vector 默认构造函数可以抛出异常吗?
- 三元操作符:抛出异常和嵌套
- 重载2D数组操作符并抛出异常
- 如何查明函数模板中的赋值操作符T是否抛出异常