托管C ++中的运算符重载

时间:2013-06-04 20:28:01

标签: c++ c++-cli command-line-interface managed-c++

我的班级定义为:(摘录)

public ref class PixelFormatDescriptor
{
  public:
    PixelFormatDescriptor();
    PixelFormatDescriptor(PIXELFORMATDESCRIPTOR *pfd);

    const PIXELFORMATDESCRIPTOR* operator*(System::Drawing::GLSharp::PixelFormatDescriptor ^p)
    {
      return m_pfd;
    }
...
  private:
    PIXELFORMATDESCRIPTOR *m_pfd;
};

我试图将它与以下内容一起使用:

PixelFormatDescriptor ^pfd = new PixelFormatDescriptor();
::ChoosePixelFormat(m_hdc, pfd);

我的问题是ChoosePixelFormat期望pfd为const PIXELFORMATDESCRIPTOR *,如何修复运算符重载以允许我传递PixelFormatDescriptor ^并让它返回PIXELFORMATDESCRIPTOR *自动而不必实现命名属性或Get方法。

2 个答案:

答案 0 :(得分:1)

以下是定义相同转换运算符的方法,但作为静态方法,相信在管理域中更为标准。

static operator PIXELFORMATDESCRIPTOR* (PixelFormatDescriptor ^p)
{
    return p->m_pfd;
}

这是记录语法的页面:

http://msdn.microsoft.com/en-US/library/vstudio/047b2c75.aspx

答案 1 :(得分:0)

我在google上经历了很多页面,发现重载运算符的文档非常缺乏,但我找到了答案:

运算符重载应该是

operator const PIXELFORMATDESCRIPTOR*()
{
  return m_pfd;
}

我想我会把答案放在这里以防其他人需要这个答案。