【问题标题】:C++ Forward declaration and files designC++ 前向声明和文件设计
【发布时间】: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 文件中只写一次。

标签: c++ forward-declaration


【解决方案1】:

我经常使用这种技术并取得了巨大的成功。

并回答“为什么不直接声明它”这个问题?有时很难转发声明。例如,如果一个类是模板类,则前向声明必须包括模板参数以及类名。

【讨论】:

  • 嗯,我怀疑这是否有用!我会遵循@JBL 的建议。至少当用户需要使用该类时,他应该熟悉所提供的所有模板参数,并且应该能够编写适当的前向类声明。
  • 如果你打算使用它,那么确保你应该知道细节,你可以通过包含类的主头文件来获得这些细节。如果您打算将引​​用或指向它的指针作为参数传递,那么在大量其他头文件中复制模板参数将是维护的噩梦。
  • '维护'这是一个论点,是的!
猜你喜欢
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
  • 2021-12-25
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多