4

Possible Duplicate:
Operator overloading outside class

I'm not great with C++ but I've been tasked with creating a custom Vector class that uses a lot of operator overloads. I'm having a hard time grasping how to do one of them. The class should provide functions for the following:

v3 = v2 * 2.0f;
v3 = 2.0f * v2;

I successfully implemented the first one by overloading the * operator. I'm not sure how to go about the second one though. I know I need to overload the * operator again, but I don't think it should be inside of my vector class. I was absent from class the day my professor explained it, and when I talked to him afterwards he mentioned that it needs to be outside of the class. The problem is that I have no idea how that will work. Any guidance would be great!

EDIT-

@Fede_Reghe That makes sense to me, but when I added it I am now getting this error from the compiler: Vector.h:64: error: passing ‘const Vector’ as ‘this’ argument of ‘float Vector::operator’ discards qualifiers

In the header, I have these two lines that refer to the * overloads. Vector operator * (float); friend Vector operator*(float, const Vector&);

Then I overloaded the [] so that it returns a float of the x, y, or z value. That looks like this in the header: float operator [] (int);

Outside of the class, I defined the friend * overload like this:

Vector operator * (float f,const Vector& v2)
 {
    float newX = v2[0] * f;
    float newY = v2[1] * f;
    float newZ = v2[2] * f;
    Vector newVector(newX, newY, newZ);
    return newVector;
 }

I don't fully understand what the error message means.

Community
  • 1
  • 1
FlapsFail
  • 525
  • 1
  • 5
  • 11

2 Answers2

3

You should overload operator outside class and declare it as friend of the class. For example:

class Vector {
     // ...
     friend Vector operator*(float, Vector);
};

Vector operator*(float num1, Vector num2)
{
    // ...
} 
ocirocir
  • 3,543
  • 2
  • 24
  • 34
2

You need the two-argument implementation of operator *(). Here is an example of doing so with operator +() that you can generalize.

mwigdahl
  • 16,268
  • 7
  • 50
  • 64