gpt4 book ai didi

C++ 前向声明和文件设计

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:29 26 4
gpt4 key购买 nike

我已经阅读了很多关于前向声明的文章,但我仍然有一个疑问。假设我们有:

// 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 类,第一次向前声明,第二次“正常”,这对我来说听起来有点奇怪。我想知道这是否是一个好的做法,以及是否可以在项目中这样做。

最佳答案

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

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

关于C++ 前向声明和文件设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19015171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com