|
-
October 22nd, 2009, 01:08 AM
#1
Problem trying to overload Operator
So, I'm trying to overload the * operator so that I can multiply two vectors (math vectors, not data structure vectors) together.
Here is my vector class.
class Vec{
float x;
float y;
float z;
public:
Vec(){}
Vec(float X, float Y, float Z){
x = X;
y = Y;
z = Z;
}
Vec operator*(Vec b){
return Vec(this->x*b.x, this->y*b.y, this->z*b.z);
}
Vec operator*(int a){
return Vec(a*this->x, a*this->y, a*this->z);
}
Vec operator-(Vec b){
return Vec(this->x-b.x, this->y-b.y, this->z-b.z);
}
float getX(){
return x;
}
float getY(){
return y;
}
float getZ(){
return z;
}
void setX(float newX){
x = newX;
}
void setY(float newY){
y = newY;
}
void setZ(float newZ){
z = newZ;
}
};
Later In my code, I use this:
Vec R = 2 * dotProduct(L, Normal) * Normal - L;
Where L and Normal are Vec and dotProduct() returns a Vec.
Here is the error I keep getting:
error C2677: binary '*' : no global operator found which takes type 'Vec' (or there is no acceptable conversion)
Could someone please help me with this?
-
October 22nd, 2009, 01:25 AM
#2
Re: Problem trying to overload Operator
If any operator function is a member of a class the left operand of this operator must always be an instance of this class.
As you can see in this expression
Code:
Vec R = 2 * dotProduct(L, Normal)
the left operand is int.
So you should provide a global operator, which takes an integer value as a first argument and a Vec object as a second argument.
Code:
Vec operator*(int a, const Vec &b)
It can be a friend of your class.
-
October 22nd, 2009, 09:39 AM
#3
Re: Problem trying to overload Operator
Or rewrite the calculation as dotProduct() * 2 so Vec is first.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|