c++ - 运算符重载使用运算符 + 为类模板添加
问题描述
我需要一个函数来添加值以v[i]
使用 包含值和operator+
的向量。v
10,2
3
#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
解决方案
只需将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;
推荐阅读
- vba - 如何将带有 findwindow api 的 vba 宏转换为 google app 脚本?
- sql - 表中不需要的删除
- javascript - 如何在选择开始日期时自动显示截止日期
- r - 按填充组顺序排列的ggplot2条形图
- javascript - 如何在 React Saga 中检查 API 帖子的成功/错误
- javascript - 如何使用乘法函数执行指数函数?
- c - 存储在光盘中的图像文件中是否存在步幅作为图像参数?
- javascript - Redux-Native 集成未按预期工作
- flutter - Flutter 交错网格视图
- python - re.VERBOSE 和 dict