C++中具有对象名称的typedef结构的正向声明

Forward declaration of typedef struct with object names in C++

本文关键字:typedef 结构 声明 对象 C++      更新时间:2023-10-16

从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

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

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

[edit]没有看到它是typedef。然而,另一个答案是错误的:有一种方法可以(某种程度上)正向声明typedef。

您可以多重声明typedef名称,也可以同时正向声明结构名称:

typedef struct tagRECT RECT;

https://ideone.com/7K7st7

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