首页 > 解决方案 > 运算符重载使用运算符 + 为类模板添加

问题描述

我需要一个函数来添加值以v[i]使用 包含值和operator+ 的向量。v10,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++classc++11templatesoperator-overloading

解决方案


只需将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+=which mean 确实返回对Measurement<T>

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

并称它为

v[2] += 3 + 2;

推荐阅读