user63898 user63898 - 2 months ago 20
C++ Question

c++ using "*" operator no operator matches these operands

I have in my class simple operator overloading

class Vec2
{
public:
Vec2(float x1,float y1)
{
x = x1;
y = y1;
}
float x;
float y;
};

class FOO {
private:
friend Vec2 operator*(const Vec2 &point1, const Vec2 &point2)
{
return Vec2(point1.x * point2.x, point1.y * point2.y);
}

Vec2 mul(Vec2 p);
};

Vec2 FOO::mul(Vec2 p)
{
Vec2 point = p * Vec2(1,-1);
return point;
}


But this multiplication gives me this error:


operator*
no operator matches these operands


The problem is i can't change the Vec2 class , so i need global operator overloading

M.M M.M
Answer

The operator* definition should not be inside class FOO. Put it outside of any class definition:

inline Vec2 operator*(const Vec2 &point1, const Vec2 &point2)
{
    return Vec2(point1.x * point2.x, point1.y * point2.y);
}

You need the inline keyword if this is in a header file. Then you can use the operator from within FOO and anywhere else.

It's not possible to restrict the operator to be usable only from within FOO methods. Function visibility doesn't work that way. The closest you could do would be to only have the operator* overload declared in some .cpp file that also has the point of usage, and mark it as static or anonymous namespace.

Comments