你可以在C ++ OOP中'重载'吗?

时间:2012-11-10 10:48:44

标签: c++ oop casting operator-overloading assignment-operator

嗯,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?或者可能是其他一些方法来实现这个目标?

3 个答案:

答案 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;
   }
};