BRabbit27
BRabbit27

Reputation: 6623

Multiplication operator overloading

I am implementing a class Vector and defined the multiplication operator as a member of the class as

Vector operator*(const float& s);

as far as I understand, this means that the left operand is a Vector and the right operand is a float. So if I try and do something like this

Vector c(1,2,3);
Vector d = c * 2.0f; // Results in d = (2,4,6)

that's ok, however, to my eyes is weird to see first the vector then the scaling factor, so in order to have float * Vector I defined a non-member function as

Vector operator*(const float& s, const Vector& v)
{
    //Invalid operands to binary expression 'const Vector' and 'float'
    return v * s;
}

However I received the error in the comment. I don't know what am I missing or if this is not the way I should declare the operator in order to do the scaling in float * Vector fashion.

Upvotes: 3

Views: 4316

Answers (2)

maqs
maqs

Reputation: 434

#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;
}

Upvotes: 1

Notice that you're passing v as const Vector &, but your member operator* is not marked as const. So it can only be called on non-const Vector objects. This is most certainly not what you want, so just mark the member as const:

Vector operator*(const float& s) const;

Upvotes: 8

Related Questions