Operator Overloading questions

So I have been working on a Vector3D class, and to enhance usability, I have been overloading operators to define such functions as dot product cross product and such. The only trouble I've had is defining the scalar product.

In math, if a is a scalar (a single number) and v is a vector with components v1,v2,v3, a * v should multiply all the elements by a.

a * v

should do

a * [v1] = [a * v1]
a * [v2] = [a * v2]
a * [v3] = [a * v3]

In code, I want to write this:
1
2
3
double a = 4;
Vector3D myVector(1,1,1);
Vector3D result = a * myVector; //result should be (4,4,4) 

The problem is that I don't know how to overload the * operator if the instance is on the right hand side of the * operator. I can define it the other way no problem.
1
2
3
Vector3D v(1,1,1);
v = v * 3; //Compile problem
v = 3 * v; //Compiles fine 

Is there a way to get the v = v * 3; to work?
Last edited on
You may want to make a friend function to overload the multiplication. That way, you can have

friend void operator*(Vector3D vec, int num);

as well as

friend void operator*(int num, Vector3D vec);
Don't return 'void'. Return 'Vector3D'.

With the Vector3D on the left, you can leave that as a class function. However, with the double on the left, you'll have to use a friend function.
1
2
3
4
5
6
7
class Vector3D {
  ...
  public:
    Vector3D operator * ( double k );                      // v = v * k
    friend Vector3D operator * ( double k, Vector3D& v );  // v = k * v
  ...
  };


Since multiplication is commutative on vectors, might as well use the previous definition:
1
2
3
Vector3D operator * ( double k, Vector3D& v ) {
  return v * k;
  }


Hope this helps.
Last edited on
Topic archived. No new replies allowed.