乘法运算符重载
Multiplication operator overloading
我正在实现一个类Vector,并将乘法运算符定义为类的成员作为
Vector operator*(const float& s);
据我所知,这意味着左操作数是一个Vector
,右操作数是float
。所以如果我尝试做一些类似的事情
Vector c(1,2,3);
Vector d = c * 2.0f; // Results in d = (2,4,6)
然而,这没关系,在我看来,先看向量,然后看比例因子是很奇怪的,所以为了得到float * Vector
,我定义了一个非成员函数作为
Vector operator*(const float& s, const Vector& v)
{
//Invalid operands to binary expression 'const Vector' and 'float'
return v * s;
}
然而,我收到了评论中的错误。我不知道我缺少了什么,或者这不是我应该声明运算符的方式,以便以float * Vector
的方式进行缩放。
v
传递为const Vector &
,但您的成员operator*
未标记为const
。因此,它只能在非常量的Vector
对象上调用。这肯定不是您想要的,所以只需将成员标记为const
:
Vector operator*(const float& s) const;
#include <iostream>
#include <vector>
using namespace std;
class Vector {
public:
float x, y, z;
Vector(float _x = 0.0f, float _y = 0.0f, float _z = 0.0f) : x(_x), y(_y), z(_z) {}
// vector + vector
Vector operator+(const Vector& v) const {
return Vector(x + v.x, y + v.y, z + v.z);
}
// vector * float
Vector operator*(float scalar) const {
return Vector(x * scalar, y * scalar, z * scalar);
}
// This friend function does the magic of float * vector
friend Vector operator*(float scalar, const Vector& v) {
return v * scalar;
}
void print() const {
cout << "(" << x << ", " << y << ", " << z << ")" << endl;
}
};
int main() {
Vector v1(1.0f, 2.0f, 3.0f);
Vector v2 = 2.0f * v1;
v2.print(); // prints (2, 4, 6)
return 0;
}
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用