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

问题描述 投票:1回答:2

从WinAPI考虑这个类:

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

我在一个名为Rect的类中增强它,它允许你乘以/加/减/比较两个Rects,以及其他功能。我需要我的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

c++ winapi struct typedef forward-declaration
2个回答
3
投票

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

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

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


3
投票

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

typedef struct tagRECT RECT;

https://ideone.com/7K7st7

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

© www.soinside.com 2019 - 2024. All rights reserved.