嗯,WinAPI有一个POINT
结构,但我正在尝试为此创建一个替代类,以便您可以从构造函数中设置x
和y
的值。这很难用一句话来解释。
/**
* 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;
是否可以通过某种方式重载operator=
,以便将Point
分配给POINT
?或者可能是其他一些方法来实现这个目标?
答案 0 :(得分:4)
您可以向Point
类添加强制转换运算符:
class Point {
// as before
....
operator POINT () const {
// build a POINT from this and return it
POINT p = {X,Y};
return p;
}
}
答案 1 :(得分:4)
这是类型转换运算符的工作:
class Point {
public:
int X, Y;
//...
operator POINT() const {
POINT pt;
pt.x = X;
pt.y = Y;
return pt;
}
};
答案 2 :(得分:0)
使用转换运算符:
class Point
{
public:
operator POINT()const
{
Point p;
//copy data to p
return p;
}
};