foo类;在头文件中 [英] class foo; in header file

查看:111
本文介绍了foo类;在头文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释为什么头文件有这样的东西吗?

Is some one able to explain why header files have something like this?

class foo; // This here?
class bar
{
   bar();

};

使用此语句时是否需要包含语句?

Do you need an include statement when using this?

谢谢.

推荐答案

第一个class foo;被称为 foo类的前向声明.它只是让编译器知道它的存在并为一个类命名.这使foo成为所谓的不完整类型"(除非已经看到foo的完整声明).对于不完整的类型,可以声明该类型的指针,但不能分配该类型的实例或执行任何需要知道其大小或成员的操作.

The first class foo; is called a forward declaration of the class foo. It simply lets the compiler know that it exists and that it names a class. This makes foo what is called an "incomplete type" (unless the full declaration of foo has already been seen). With an incomplete type, you can declare pointers of that type, but you cannot allocate instances of that type or do anything that requires knowing its size or members.

这种前向声明经常在两种类型可能彼此指向的情况下使用,在这种情况下,两种类型都需要能够表达指向另一种类型的指针的概念,因此如果没有此类,则将具有循环依赖关系一个东西.这是最需要的,因为C ++使用单次通过机制来解析类型.在Java中,由于Java使用了多次传递,因此可以具有没有前向声明的循环依赖关系.在作者误以为使用前向声明而不是包含必需的标头会减少编译时间的情况下,您可能还会看到前向声明.当然不是这种情况,因为无论如何您都需要包括完整的声明(即标头),并且如果使用了预处理器保护,则编译时间基本上没有区别.

Such forward declarations are frequently used when two types each may have pointers to each other, in which case both need to be able to express the notion of a pointer to the other type, and so you would have a circular dependency without such a thing. This is needed mostly because C++ uses a single pass mechanism for resolving types; in Java, you can have circular dependencies without forward declarations, because Java uses multiple passes. You may also see forward declarations where the author is under the misguided impression that using forward declarations instead of including the required header reduces compile time; that, of course, is not the case, because you need to include the full declaration (i.e. the header), anyway, and if preprocessor guards are used, then there is basically no difference in compile time.

要回答您是否需要包含的问题……假设您只需要部分类型,那么您的标头就不必直接包含已被向前声明的类型的标头;但是,无论谁使用您的标头,当他们使用您的类型时,都需要包括正向声明类型的标头,因此您最好也包含其他标头.

To answer your question on whether you need the include or not... assuming you only need a partial type, then your header does not need to directly include the header for the type that has been forward declared; however, whoever makes use of your header, when they use your type will need to include the header for the forward declared type, and so you might as well just include the other header.

这篇关于foo类;在头文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆