乘法运算符重载

Multiplication operator overloading

本文关键字:重载 运算符      更新时间:2023-10-16

我正在实现一个类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;
}