【发布时间】:2012-11-16 01:16:01
【问题描述】:
考虑 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?
【问题讨论】:
-
只是一个注释。我做了同样的事情,我还想要一个 RECT 结构的增强版本。最后我的结构是从 RECT 派生的,因为当使用期望 RECT 作为参数的 winapi 函数时不需要转换。我发现这是一个更好的解决方案,您可能会考虑到这一点
-
@user1017443 这是个好主意。我最初考虑过它,但我决定反对它,因为我想要 'Width' 和 'Height' 而不是 'cx' 和 'cy'。哪一个,这可能不是一个很好的借口,因为这种方式需要更多的课堂用户写作。
-
但无论哪种方式都需要在文件中包含“
”。 -
您仍然可以定义名为 Width 的成员函数,这些函数只返回 RECT 结构的成员。是的,从用户的角度来看,派生更容易。
标签: c++ winapi struct typedef forward-declaration