c++ 中的前向声明是什么?
这个答案说:
…最后,
typedef struct { ... } Foo;
声明一个匿名结构并为其创建一个 typedef。因此,对于此构造,它在标记命名空间中没有名称,只有 typedef 命名空间中的名称。这意味着它也不能被提前声明。如果你想进行前向声明,你必须在标签命名空间中给它一个名称。
什么是前向声明?
This answer says:
… Finally,
typedef struct { ... } Foo;
declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also can't be forward-declared. If you want to make a forward declaration, you have to give it a name in the tag namespace.
What is forward declaration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
查德在字典中给出了一个很好的定义。 C++ 中经常使用前向声明来处理循环关系。例如:
Chad has given a pretty good dictionary definition. Forward declarations are often used in C++ to deal with circular relationships. For example:
“在计算机编程中,前向声明是程序员尚未给出完整定义的标识符声明(表示类型、变量或函数等实体)。”
-维基百科
"In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, or a function) for which the programmer has not yet given a complete definition."
-Wikipedia
据我所知,在 C++ 中 “前向声明”一词用词不当。它只是一个声明,使用了一个奇特的名称。
To the best of my knowledge, in C++ the term "forward declaration" is a misnomer. It's simply a declaration under a fancy name.
前向声明在实际定义之前声明标识符(将其放入命名空间中)。如果需要在定义结构之前使用指向结构的指针,则需要向前声明结构。
在您链接的答案的上下文中,如果您有
typedef struct {...} Foo;
,则不能在结构内部或 typedef 语句结束之前使用指向 Foo 的指针。另一方面,您可以
typedef struct tagFoo Foo;
以及稍后的struct tagFoo {...};
A fowrard declaration declares the identifier (puts it in a namespace) before the actual definition. You need forward declaration of structs if you need to use a pointer to the struct before the struct is defined.
In the context of the answer you linked, if you have
typedef struct {...} Foo;
, you cannot use a pointer to Foo inside the struct or before the end of the typedef statement.On the other hand you can
typedef struct tagFoo Foo;
and laterstruct tagFoo {...};
当类成员使用其中另一个类的引用时,需要前向声明。例如:
Forward declaration is needed when a class member uses a reference of another class in it. E.g.: