#### Archived

This topic is now archived and is closed to further replies.

# operators in classes

This topic is 6932 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi i have a little problem with operator overloading in classes here: in my class Vector i have this function:Vector Vector::operator* ( float f ) with this i can make statements such as Vector a; Vector b = a * 2; but what please do i have to do if i want get a statement like b = 2 * a to work?? This only gives me an error that no global operator is defined that accepts ''class Vector'' So does anyone know how i have to define my function to get it to work? Thanks for your help, Burning_Ice

##### Share on other sites
I''m a little bit rusty, because it''s been a while since I''ve done this, but I believe you define a global function that has both operands listed:
Vector operator*(float a, Vector v)
and you''ll be ok.

I could be wrong though. Like I said, it''s been a while since I''ve done it.

##### Share on other sites
Something like this:

class Vector {   /* data here */public:   /* constructors, etc */   friend Vector operator*(float f, const Vector& v);   friend Vector operator*(const Vector& v, float f);};/* somewhere outside of the class */Vector operator*(float f, const Vector& v){  Vector result;  /* calculate value, store in result */  return result;}/* do same for other version of operator* */

---- --- -- -

##### Share on other sites
Make sure you''ve defined your copy constructor and assignment operator.

Vector::operator =(Vector &a, Vector &b)

and yes, you have to define a function that will accept two vector operands, and if you want to use it fora vector times an integer, you have to define a separate function as well

Vector::operator *(Vector &a, Vector &b);
Vector::operator *(Vector &a, int &b);

get it I hope? Operators that only need one parameter are operators like ++

DarkAgito

##### Share on other sites
yes when you overload an operator and want it to work with a specific class, you need to declare it as a friend to the class, but not a member.

##### Share on other sites
operators should be declared as member functions of the class when the class will be the left hand operator (like the assignment operator, which must be a member function). If the class is a right hand member and a different object is a left hand member, make the function a friend of the class. And make sure copy and assignment operators are defined too.

class X{  int y;public:  X() : y(0) {}  X(int i) : y(i) {}  X(const X& other) : y(other.y) {}  X& operator = (const X& other)     { y=other.y; return *this; }  bool operator == (const int right)    { return y==right; }  friend bool operator == (const int left, const X right); //...};bool operator == (const int left, const X right){ return left==right.y; }

• 15
• 13
• 35
• 39