hkB*_*sai 5 c++ operator-overloading matrix
我有一个数学矩阵类.它包含一个成员函数,用于访问该类的任何元素.
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
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的代码中使用此方法,如下所示:
// 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);
Run Code Online (Sandbox Code Playgroud)
这很好用,但我想使用运算符重载来简化操作,如下所示:
Matrix<double> matrix(2, 3);
matrix(1, 2) = 6.78; // HOW DO I DO THIS?
Run Code Online (Sandbox Code Playgroud)
返回对重载中元素的引用operator()。
template<class T>
class Matrix
{
public:
T& operator()(uint64_t unRow, uint64_t unCol);
// Implement in terms of non-const operator
// to avoid code duplication (legitimate use of const_cast!)
const T&
operator()(uint64_t unRow, uint64_t unCol) const
{
return const_cast<Matrix&>(*this)(unRow, unCol);
}
};
template<class T>
T&
Matrix<T>::operator()(uint64_t unRow, uint64_t unCol)
{
// return the desired element here
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
617 次 |
| 最近记录: |