本文介绍了为什么包含一个头文件并向前声明包含在同一个cpp文件中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为我的大学项目寻找恐惧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 --- 
模板< 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'在这里有一个前面的声明
$ b

这是我总推荐使用专用前向声明头文件ala < iosfwd> #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文件中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:10