problem defining = operator

Started by
1 comment, last by ToohrVyk 15 years, 9 months ago
Hey. From the code it is easy to see what I'm trying to do. But this isn't working! I get the error: " C:\Users\Remy\Documents\CPP Enterprise game\geometry.h|43|error: no match for 'operator=' in '((Rect*)this)->Rect::start = (((Vector2D*)operator new(16u)), (<anonymous>->Vector2D::Vector2D(), <anonymous>))" Code: class Vector2D { public: double x; double y; public: Vector2D& operator= (const Vector2D& param) { x=param.x; y=param.y; return *this; } }; class Rect { public: Vector2D start; Vector2D end; Rect() {start = new Vector2D(); end = new Vector2D();} };
Advertisement
Because new returns pointers to Vector2D's, but you have full objects, not pointers. This is unrelated to operator=().
C++ uses value semantics: the members are created when the object is created. The default constructor, as well as the default assignment operator, already do what you need. Therefore, you could simply write:

struct Vector2D {  double x;  double y;};struct Rect {  Vector2D start;  Vector2D end;};


I changed "class Foo { public:" to "struct Foo {" because it's shorter.

This topic is closed to new replies.

Advertisement