【问题标题】:Can you 'overload a cast' in C++ OOP?您可以在 C++ OOP 中“重载演员表”吗?
【发布时间】:2012-10-30 13:22:14
【问题描述】:

好吧,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?或者可能有其他方法来实现这一点?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我实际上不知道有一个转换运算符。我想这一切都归结为你不知道你不知道的东西,如果这有任何意义的话;)
    • 您也可以从 POINT 结构或类派生。这为您提供了对 POINT& 的隐式转换以及将 Point* 隐式转换为 POINT* 的能力。
    • @Yakk 的建议是 ATL 实际做了什么来为 VARIANTBSTR 提供一个(糟糕的)C++ 包装器。对于CComSafeArray,他们使用了转换运算符。
    【解决方案2】:

    您可以在 Point 类中添加强制转换运算符:

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

    【讨论】:

      【解决方案3】:

      使用转换运算符:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-04
        • 1970-01-01
        • 1970-01-01
        • 2019-03-25
        • 2012-10-24
        • 1970-01-01
        • 2017-06-20
        相关资源
        最近更新 更多