【发布时间】:2013-10-01 15:36:20
【问题描述】:
我已经阅读了很多关于前向声明的文章,但我仍然有一个问题。 假设我们有:
// File a.hpp (in this question I avoid writing guards in header files, for the sake of simplicity)
class A
{
// Class B is used only by pointer, the compiler doesn't need to know the structure
// of the class, so a forward declaration is enough
public:
A(void);
void Method1(B *pB);
void Method2(B *pB);
};
// File a.cpp
#include "a.hpp"
A::A(void) { }
// Some methods of class B are used, so the compiler needs to know the declaration of the class, it cannot be forward declared
void A::Method1(B *pB)
{
// Something...
pB->SomeMethod();
// Something ...
}
void A::Method2(B *pB)
{
int var = pB->GetSomeMember();
// Something ...
}
好的,现在假设有一个头文件用于 B 类声明,另一个头文件用于其前向声明:
// File b.hpp
// Class declaration
class B
{
/* ... */
};
// File b_fwd.hpp
// Forward declaration
class B;
基于前面的考虑,我的想法是在 a.hpp 中包含“b_fwd.hpp”(只需要 B 类的前向声明),在 a.cpp 中包含“b.hpp”文件(需要声明), 如下:
// File a.hpp
#include "b_fwd.hpp" // Forward declaration of class B
class A
{
public:
A(void);
void Method1(B *pB);
void Method2(B *pB);
};
// File a.cpp
#include "a.hpp"
#include "b.hpp" // Declaration of class B
A::A(void) { }
void A::Method1(B *pB) { /* like before ... */ }
void A::Method2(B *pB) { /* like before ... */ }
我知道这是可行的,但是由于在 A 类中我包括(假设)“两次”B 类,第一次向前声明,第二次“正常”,这对我来说听起来有点奇怪。我想知道这是否是一个好的做法,是否可以在项目中完成。
【问题讨论】:
-
为什么不直接在
a.hpp中转发声明class B呢?您认为将其放在单独的标题中可以实现什么?请注意,#include "some_file"指令基本上使预处理器在编译阶段之前将some_file的内容复制到具有该指令的文件中。 -
我知道,但我更喜欢将其“封装”到 .hpp 文件中。例如,如果有命名空间或模板,我不想每次都写它们,但我不想每次都写它们,但我在 .hpp 文件中只写一次。