在 typedef 中使用类型时包含在头文件中的规则
如果我
typedef double (MyClass::*MemFuncGetter)();
在头文件中创建,是否需要包含“MyClass.h”或者前向声明就足够了?
头文件:
#ifndef _TEST_
#define _TEST_
#include "MyClass.h" //do I need this?
//or I can just say class MyClass;
typedef double (MyClass::*MemFuncGetter)();
#endif
这里的链接规则是什么?
if I create
typedef double (MyClass::*MemFuncGetter)();
in a header file, do I need to include "MyClass.h" or would forward declaring suffice?
Header file:
#ifndef _TEST_
#define _TEST_
#include "MyClass.h" //do I need this?
//or I can just say class MyClass;
typedef double (MyClass::*MemFuncGetter)();
#endif
What are the linkage rules here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只需要类的前向声明即可:
但请注意,如果不包含整个类,编译器必须做额外的工作来处理 MyClass 是多重虚拟继承混乱的情况,因为它不知道。 在某些情况下,这可能意味着每个函数指针实际上占用最多 20 字节的内存。 然而,如果您定义了整体,则每个函数指针只需要 4 个。(当然,大小都取决于编译器)。
You are fine with just the forward declaration of the class:
But note that by not including the whole class, the compiler has to do extra work to handle the cases when MyClass is a multiple-virtual inheritance mess, since it doesn't know. In some cases this can mean that each function pointer actually takes up to 20 bytes of memory. Whereas if you had defined the whole, each function pointer would only take 4. (Of course the sizes are all compiler-dependant).
您需要在范围内至少有一个
MyClass
声明——至少是一个前向声明。 Typedef 创建一个别名。 它不会创建新类型或更改链接。 该链接将是MemFuncGetter
的链接。You need to have at least a declaration of
MyClass
in scope -- a forward declaration at least. Typedef create an alias. It does not create a new type or change the linkage. The linkage will be that ofMemFuncGetter
.是的,向前声明就足够了。
Yes forward declraing will enough.
创建文件 MyClassFwd.h 并将其放在那里
并包含前向 decl - 这就足够了。 不要复制并粘贴 typedef。 在您的“MyClass.h”中只需包含“MyClassFwd.h”
Create file MyClassFwd.h and put there
And include forward decl - that will be enough. Don't copy and paste typedef. In your 'MyClass.h' simply include 'MyClassFwd.h'