使用C ++中的对象名转发typedef结构的声明

时间:2012-11-16 01:16:01

标签: c++ winapi struct typedef forward-declaration

从WinAPI考虑这个类:

typedef struct tagRECT
{
    LONG    left;
    LONG    top;
    LONG    right;
    LONG    bottom;
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;

我在名为Rect的类中对其进行了增强,该类允许您将两个Rect与其他功能相乘/加/减/比较。我需要Rect课程了解RECT的唯一真正原因是因为该课程具有转化运算符,允许将Rect作为RECT传递,并且被分配RECT

但是,在文件Rect.h中,我不想包含<Windows.h>,我只想在源文件中包含<Windows.h>,以便我可以保持包含树的小。

我知道结构可以像这样向前声明:struct MyStruct; 但是,结构的实际名称是tagRECT并且它有一个对象列表,所以我对如何转发声明它感到困惑。这是我班级的一部分:

// Forward declare RECT here.

class Rect {
    public:
        int X, Y, Width, Height;

        Rect(void);
        Rect(int x, int y, int w, int h);
        Rect(const RECT& rc);

        //! RECT to Rect assignment.
        Rect& operator = (const RECT& other);

        //! Rect to RECT conversion.
        operator RECT() const;

        /* ------------ Comparison Operators ------------ */

        Rect& operator <  (const Rect& other);
        Rect& operator >  (const Rect& other);
        Rect& operator <= (const Rect& other);
        Rect& operator >= (const Rect& other);
        Rect& operator == (const Rect& other);
        Rect& operator != (const Rect& other);
};

这会有效吗?

// Forward declaration
struct RECT;

我的想法是否定的,因为RECT只是tagRECT的别名。我的意思是,我知道如果我这样做,头文件仍然有效,但是当我创建源文件Rect.cpp并在那里包含<Windows.h>时,我担心这是我将遇到问题的地方。

我怎样才能转发声明RECT

2 个答案:

答案 0 :(得分:3)

您可以乘法声明一个typedef名称,并同时转发声明结构名称:

typedef struct tagRECT RECT;

https://ideone.com/7K7st7

请注意,您无法调用返回不完整类型的函数,因此如果operator RECT() const仅向前声明,则无法调用转换tagRECT

答案 1 :(得分:3)

在实际解除引用类型之前,您不需要知道函数定义。

因此,您可以在标头文件中转发声明(因为您不会在此处进行任何解除引用),然后在文件中包含Windows.h

[edit] 没看到它是一个typedef。但是,另一个答案是错误的:there is a way to (kind of) forward declare a typedef

相关问题