在 typedef 中使用类型时包含在头文件中的规则

发布于 2024-07-15 00:42:36 字数 363 浏览 7 评论 0原文

如果我

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

葮薆情 2024-07-22 00:42:36

您只需要类的前向声明即可:

#ifndef _TEST_
#define _TEST_

class MyClass;
typedef double (MyClass::*MemFuncGetter)();

#endif

但请注意,如果不包含整个类,编译器必须做额外的工作来处理 MyClass 是多重虚拟继承混乱的情况,因为它不知道。 在某些情况下,这可能意味着每个函数指针实际上占用最多 20 字节的内存。 然而,如果您定义了整体,则每个函数指针只需要 4 个。(当然,大小都取决于编译器)。

You are fine with just the forward declaration of the class:

#ifndef _TEST_
#define _TEST_

class MyClass;
typedef double (MyClass::*MemFuncGetter)();

#endif

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).

你怎么敢 2024-07-22 00:42:36

您需要在范围内至少有一个 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 of MemFuncGetter.

在你怀里撒娇 2024-07-22 00:42:36

是的,向前声明就足够了。

Yes forward declraing will enough.

我还不会笑 2024-07-22 00:42:36

创建文件 MyClassFwd.h 并将其放在那里

class MyClass;
typedef double (MyClass::*MemFuncGetter)();

并包含前向 decl - 这就足够了。 不要复制并粘贴 typedef。 在您的“MyClass.h”中只需包含“MyClassFwd.h”

Create file MyClassFwd.h and put there

class MyClass;
typedef double (MyClass::*MemFuncGetter)();

And include forward decl - that will be enough. Don't copy and paste typedef. In your 'MyClass.h' simply include 'MyClassFwd.h'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文