cannot overload assignment operator

gandalf3373
gandalf3373 used Ask the Experts™
on
i have a simple vector class, 3 float members x,y,z. i want to overload the assignment operator so i can do vector1 = vector2 in an app.
anyways the compiler is not recognizing the operator function although the function itself does compile. here is what i have, in abbreviated form.

//in header file
void operator=(Vector& v);
//copy constructor
Vector(Vector& v);

//in .cpp file

Vector::Vector(Vector& v)
{

   x = v.x;
   y = v.y;
   z = v.z;

}

void Vector::operator=(Vector& v)
{
   x = v.x;
   y = v.y;
   z = v.z;
}

vc++ 6.0 says there is no binary = operator that takes an operand of class Vector as an rvalue, although all of the above functions compile.

the line that generates the error is in another class something that is essentially,

vector1 = vector2;

i must be doing something wrong, but i am not sure what, any help would be greatly appreciated.

james

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2012
Commented:
Try

Vector& Vector::operator=(const Vector& v)
{
  x = v.x;
  y = v.y;
  z = v.z;

  return *this;
}

Commented:
and while you're at it, change your copy constructor to be

Vector::Vector(const Vector& v)
{
  *this = v;
}

it'll be both more accurate (because the parameter should be const Vector& and not just Vector&) and more code reusable cuz you'll need to change only the assignment operator when the class' strcture changes, and not both the operator and the copy constructor.

Just my two cents :)

Commented:
you might be interested in this:

http://members.cox.net/jrocnuck/algebra3.h

Author

Commented:
i think the way i was doing it would have worked, allthough it may not have been the best practice. my problem was using the operator to assign pointers that had not had
any memory allocated to them yet. anyways, take the points for answering.

james
jkr
Top Expert 2012

Commented:
Thank you!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial