【发布时间】:2023-03-14 20:21:01
【问题描述】:
我有一个数学矩阵类。它包含一个成员函数,用于访问类的任何元素。
template<class T>
class Matrix
{
public:
// ...
void SetElement(T dbElement, uint64_t unRow, uint64_t unCol);
// ...
};
template <class T>
void Matrix<T>::SetElement(T Element, uint64_t unRow, uint64_t unCol)
{
try
{
// "TheMatrix" is define as "std::vector<T> TheMatrix"
TheMatrix.at(m_unColSize * unRow + unCol) = Element;
}
catch(std::out_of_range & e)
{
// Do error handling here
}
}
我在我的代码中使用这种方法,如下所示:
// create a matrix with 2 rows and 3 columns whose elements are double
Matrix<double> matrix(2, 3);
// change the value of the element at 1st row and 2nd column to 6.78
matrix.SetElement(6.78, 1, 2);
这很好用,但我想使用运算符重载来简化事情,如下所示:
Matrix<double> matrix(2, 3);
matrix(1, 2) = 6.78; // HOW DO I DO THIS?
【问题讨论】:
-
只是一个小错误:
template <class T> -
为什么不重载运算符[]?
-
@DeadMG: 因为
operator[]只带一个参数? -
@jalf:虽然可以很容易地被链接起来,比如矩阵[1][2],就像一个常规数组。
-
@DeadMG:可能,但重载
operator()更容易。
标签: c++ matrix operator-overloading