[英]How do I overload () operator with two parameters; like (3,5)?
I have a mathematical matrix class. 我有一个数学矩阵类。 It contains a member function which is used to access any element of the class.
它包含一个成员函数,用于访问该类的任何元素。
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
}
}
I'm using this method in my code like this: 我在我的代码中使用此方法,如下所示:
// 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);
This works well, but I want to use operator overloading to simplify things, like below: 这很好用,但我想使用运算符重载来简化操作,如下所示:
Matrix<double> matrix(2, 3);
matrix(1, 2) = 6.78; // HOW DO I DO THIS?
Return a reference to the element in the overloaded operator()
. 返回对重载
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.