重载对象前面带有数字的运算符+(int)
Overload operator+(int) with number before object
我有一个vec2类,定义如下
class vec2 {
public:
float x, y;
...
//add a scalar
vec2 operator+(float s) const {
return vec2(this->x + s, this->y + s);
}
};
运算符+重载在执行vec2 v = otherVector * 2.0f;
时效果良好,但在向后执行时不起作用,就像vec2 v = 2.0f * otherVector;
一样。
解决这个问题的办法是什么?
以您的示例为例,表达式
otherVector * 2.0f
相当于
otherVector.operator+(2.0f)
将重载运算符创建为成员函数only允许对象位于左侧,右侧传递给函数。
简单的解决方案是添加另一个运算符重载,作为非成员函数
vec2 operator+(float f, const vec2& v)
{
return v + f; // Use vec2::operator+
}
相关文章:
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 运算符 += 应用于 std::valarray<int*>
- 我的运算符重载没有在我的 int main 中返回?
- 类型"int"和"const char [15]"到二进制"运算符<<"的无效操作数^
- 使用算术运算符时如何避免从 char 到 int 的隐式转换
- ostream_iterator运算符=在pair<int,int>上失败,但在包装器类上工作。我不能为成对<>重载运算符<<吗?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 运算符[]和运算符int()的不明确重载
- 二进制 '[':未找到采用 'const SortableVector' 类型的左操作数的运算符<int>
- 是否可以为带有 std:string 和 std::vector 的 std::map 重载<<运算符<int>?
- GCC 无法区分运算符++() 和运算符++(int)
- 是否可以完全模拟虚拟运算符++(int)?
- 运算符++()和运算符++(int)之间的区别是什么
- 重载c++运算符int/foat(.)
- 筛选的const_iterator运算符++(int)
- static_cast和interpret_cast的转换运算符int()失败
- 使用 google mock 模拟转换运算符 int()
- 重载对象前面带有数字的运算符+(int)
- 运算符 [](int i) 中的边界检查
- C++使用运算符int()而不是运算符+