问题描述
我一直在为我的大学项目寻找恐惧SDK,但已经注意到一些类似的代码:
Foo.h
class Foo
{
public:
int iSomething;
};
Bar.cpp:
#includeFoo.h
//正向声明
class Foo;
是否有任何特别的理由来转发declare AND在相同的cpp文件中包含适当的头文件?或者是前面的声明是多余的,因为头文件被包含在内?
编辑:每次我有在代码中看到它,include声明总是在前向声明之前。
它不仅仅是多余的,它可能有问题。说Foo.h发生了变化,所以Foo变成了一种泛型模板化等价物的特定实例化的类型定义 - 这是可以作为正常软件进化的一部分而预料到的东西。然后Bar.cpp的class X将不必要地导致编译错误ala:
--- fwd.h ---
$ b
模板< typename T>
class XT
{
public:
int n_;
};
typedef XT< int> X;
--- fwd.cc ---
#includefwd.h
class X;
int main()
{
X x;
x.n_ = 0;
return x.n_;
}
---编译尝试---
〜/ dev ... / gcc / 4.1.1 / exec / bin / g ++ fwd.cc -o fwd
fwd.cc:3:错误:在'class'后面使用typedef-name'X'
fwd.h:8:错误:'X'在这里有一个前面的声明
这是我总推荐使用专用前向声明头文件ala
< iosfwd> $ c $与主标题保持并包括在一起以确保持续的一致性。我从来没有放过X班在实现文件中,除非在那里定义类。请记住,X类的看似好处;前向声明不是很多,它们避免了
#include
,更多的是它们包含的文件可能很大,并且包含许多其他文件:专用前向声明无论如何,标题通常会避免绝大多数。I've been looking at the Fear SDK for my university project, but have noticed some code like so:
Foo.h
class Foo { public: int iSomething; };
Bar.cpp:
#include "Foo.h" // Forward declarations class Foo;
Is there any particular reason to forward declare AND include the appropriate header in the same cpp file? Or is the forward declaration redundant because the header is being included?
EDIT:
Every time that I have seen it in the code, the include statement is always before the forward declaration.
解决方案It's more than simply redundant, it's potentially problematic. Say Foo.h changes so Foo becomes a typedef to some particular instantiation of a generic, templatised equivalent - the kind of thing that can be anticipated as part of normal software evolution. Then Bar.cpp's "class X" will needlessly cause a compilation error ala:
--- fwd.h --- template <typename T> class XT { public: int n_; }; typedef XT<int> X; --- fwd.cc --- #include "fwd.h" class X; int main() { X x; x.n_ = 0; return x.n_; } --- compilation attempt --- ~/dev .../gcc/4.1.1/exec/bin/g++ fwd.cc -o fwd fwd.cc:3: error: using typedef-name 'X' after 'class' fwd.h:8: error: 'X' has a previous declaration here
This is one reason I always recommend using dedicated forward-declaration headers ala
<iosfwd>
, maintained with and included by the main header to ensure ongoing consistency. I never put "class X;" in an implementation file unless the class is defined in there too. Remember that the seeming benefits of "class X;" forward declarations is not so much that they avoid an#include
, and more that the files they include can be large and in turn include a lot of other files: dedicated forward-declaration headers typically avoid the overwhelming majority of that anyway.这篇关于为什么包含一个头文件并向前声明包含在同一个cpp文件中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!