C++中具有对象名称的typedef结构的正向声明
Forward declaration of typedef struct with object names in C++
从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
。
相关文章:
- 如何创建 typedef 结构的前向声明
- 无法转发声明C typedef结构-正在查找其他建议
- 如何使用 SWIG 接口访问 python 中的 C++ typedef'd 结构
- 具有未声明/未定义类型的 typedef 结构
- 在 CPP 中初始化 typedef 结构变量
- C++ 无法在 typedef 结构中重载<运算符
- 在 typedef 结构中声明一个数组
- 从 csv 文件中获取不同类型的数据,并将其放入 C++ 中的 typedef 结构中
- 为什么 typedef 结构允许默认初始值设定项?
- 为什么我不能像正常一样初始化 typedef 结构字符串或字符?
- 在Typedef结构中,下划线意味着什么
- 来自 typedef 结构的错误
- 在Typedef结构(C )中超载运算符
- C++中具有对象名称的typedef结构的正向声明
- 为什么Typedef结构会产生链路故障
- 在Typedef结构中定义结构
- 类中typedef结构的奇怪行为
- C/C++ 中的套接字编程 - 接收由 typedef 结构定义的消息
- 扩展typedef结构(与VC++11兼容)
- 为什么子类在C++中看不到父类的 typedef 结构?