3

好吧,WinAPI 有一个POINT结构,但我正在尝试为此创建一个替代类,以便您可以设置构造函数的值xy来自构造函数的值。这很难用一句话来解释。

/**
 * 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=,以便我可以将 a 分配Point给 a POINT?或者也许是其他一些方法来实现这一点?

4

3 回答 3

4

你可以在你的Point类中添加一个强制转换运算符:

class Point {
  // as before
  ....
  operator POINT () const { 
    // build a POINT from this and return it
    POINT p = {X,Y};
    return p;
  }
}
于 2012-11-10T10:51:56.107 回答
4

这是类型转换运算符的工作:

class Point {
  public:
    int X, Y;

    //...

    operator POINT() const {
        POINT pt;
        pt.x = X;
        pt.y = Y;
        return pt;
    }
};
于 2012-11-10T10:53:07.853 回答
0

使用转换运算符:

class Point 
{
public:
   operator POINT()const
   {
       Point p;
       //copy data to p
       return p;
   }
};
于 2012-11-10T10:54:29.223 回答