【问题标题】:Operators overloading add using operator+ for a class-template运算符重载使用运算符 + 为类模板添加
【发布时间】:2020-10-17 20:15:18
【问题描述】:

我需要一个函数来使用operator+v[i]添加值 向量v 包含值10,23

#include <iostream>
#include <vector>

template<typename T>
class Measurement 
{
private:
    T val;
public:
    Measurement(T a)
        : val{ a }
    {}

    T value() const { return val; }

    Measurement<T>& operator+(const T& nr) 
    {
        //... ???
        return *this;
    }

};

int main()
{
    //create a vector with values (10,2,3)
    std::vector<Measurement<int>> v{ 10,2,3 };
    v[2] + 3 + 2; //add at v[2] value 5
    for (const auto& m : v) std::cout << m.value() << ",";
    return 0;
}

结果必须是10,2,8

【问题讨论】:

    标签: c++ class c++11 templates operator-overloading


    【解决方案1】:

    只需将实例的val添加到其他nr

    Measurement<T>& operator+(const T& nr)
    {
       this->val += nr;
       return *this;
    }
    

    但是,为此重载operator+ 可能会产生误导,应该避免这种情况。因此我会建议传统的方式

    Measurement<T> operator+(const T& nr)
    {
       Measurement<T> tmp{ *this };
       tmp.val += nr;
       return tmp;  // returns the temporary, which you need to reassign!
    }
    

    然后做

    v[2] = v[2] + 3 + 2; 
    

    为了需要的结果。


    或者甚至更好地提供operator+=,这意味着确实返回对Measurement&lt;T&gt;的引用

    Measurement<T>& operator+=(const T& nr)
    {
       this->val += nr;
       return *this;
    }
    

    然后这样称呼它

    v[2] += 3 + 2;
    

    【讨论】:

    • 虽然这是正确的,但operator+ 实际上修改 元素并返回reference 会令我​​非常困惑。
    • @MikaelH 是的。这是一种误导/滥用operator+
    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    相关资源
    最近更新 更多