【问题标题】:How do I overload () operator with two parameters; like (3,5)?如何使用两个参数重载 () 运算符;像(3,5)?
【发布时间】: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 &lt;class T&gt;
  • 为什么不重载运算符[]?
  • @DeadMG: 因为operator[] 只带一个参数?
  • @jalf:虽然可以很容易地被链接起来,比如矩阵[1][2],就像一个常规数组。
  • @DeadMG:可能,但重载operator() 更容易。

标签: c++ matrix operator-overloading


【解决方案1】:

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

【讨论】:

  • 在这两种operator() 方法中,您都应该返回对实际元素的引用。亚历克斯忘记写了。第一个(不带conts)用于赋值,第二个用于从矩阵中获取值。
  • 为什么要定义两种不同的方法?我们不能用一个返回引用的方法来做吗?
  • 转发版本坏了,它返回一个临时变量的引用。
  • @Pawel:不,如果矩阵是非常量的,第一个版本用于所有访问(读取和写入矩阵)。 @hkBattousai:您认为哪种方法是多余的?它们返回两种不同的类型,一种是T&amp;,另一种是const T&amp;
  • @Ben:是的,你是对的。 @hkBattousai:如果Matrixconst 并且您将调用operator(),则会调用const 的方法。没有它,您将无法使用 operator() 从常量 Matrix 对象中获取元素。
猜你喜欢
  • 1970-01-01
  • 2015-05-10
  • 2023-03-13
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
相关资源
最近更新 更多