如何使用两个参数使用overload()运算符;喜欢(3,5)?

时间:2010-12-25 12:46:27

标签: c++ matrix operator-overloading

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

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?

1 个答案:

答案 0 :(得分:3)

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