你能在 OOP 中"超载演员表"C++吗?

Can you 'overload a cast' in C++ OOP?

本文关键字:C++ 超载 OOP      更新时间:2023-10-16

好吧,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=,以便我可以将Point分配给POINT?或者也许还有其他实现此目标的方法?

这是类型转换操作员的作业:

class Point {
  public:
    int X, Y;
    //...
    operator POINT() const {
        POINT pt;
        pt.x = X;
        pt.y = Y;
        return pt;
    }
};

您可以在Point类中添加铸件运算符:

class Point {
  // as before
  ....
  operator POINT () const { 
    // build a POINT from this and return it
    POINT p = {X,Y};
    return p;
  }
}

使用转换操作员:

class Point 
{
public:
   operator POINT()const
   {
       Point p;
       //copy data to p
       return p;
   }
};