Reputation: 2297
Well, the WinAPI has a POINT
struct, but I am trying to make an alternative class to this so you can set the values of x
and y
from a constructor. This is hard to explain in one sentence.
/**
* X-Y coordinates
*/
class Point {
public:
int X, Y;
Point(void) : X(0), Y(0) {}
Point(int x, int y) : X(x), Y(y) {}
Point(const POINT& pt) : X(pt.x), Y(pt.y) {}
Point& operator= (const POINT& other) {
X = other.x;
Y = other.y;
}
};
// I have an assignment operator and copy constructor.
Point myPtA(3,7);
Point myPtB(8,5);
POINT pt;
pt.x = 9;
pt.y = 2;
// I can assign a 'POINT' to a 'Point'
myPtA = pt;
// But I also want to be able to assign a 'Point' to a 'POINT'
pt = myPtB;
Is it possible to overload operator=
in a way so that I can assign a Point
to a POINT
? Or maybe some other method to achieve this?
Upvotes: 3
Views: 122
Reputation: 227400
You could add a cast operator to your Point
class:
class Point {
// as before
....
operator POINT () const {
// build a POINT from this and return it
POINT p = {X,Y};
return p;
}
}
Upvotes: 4
Reputation: 5546
Use conversion operator:
class Point
{
public:
operator POINT()const
{
Point p;
//copy data to p
return p;
}
};
Upvotes: 0
Reputation: 40603
This is the job of a type conversion operator:
class Point {
public:
int X, Y;
//...
operator POINT() const {
POINT pt;
pt.x = X;
pt.y = Y;
return pt;
}
};
Upvotes: 4