gpt4 book ai didi

c++ - 如何用两个参数重载 () 运算符;像(3,5)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:41:48 28 4
gpt4 key购买 nike

我有一个数学矩阵类。它包含一个成员函数,用于访问类的任何元素。

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?

最佳答案

返回对重载的 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
}

关于c++ - 如何用两个参数重载 () 运算符;像(3,5)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4530301/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com