为什么头文件不能相互包含?

Why can't header files include eachother?

本文关键字:包含 不能 文件 为什么      更新时间:2023-10-16

为什么我不能在C++中做这样的事情?

啊:

#ifndef A_H
#define A_H
#include "B.h"
struct A {
int a;
};
void doStuff1 (B b);  // Error here
#endif

B.h:

#ifndef B_H
#define B_H
#include "A.h"
struct B {
int b;
};
void doStuff2 (A a);  // Error here
#endif

我收到一个'A' was not declared in this scope的错误,'B'也是如此. 我知道前向声明,但我想看看是否有可能将这样的设置作为按值传递而不是通过引用/指针。如果编译器到达该代码时实际上已声明AB,为什么编译器的行为会像这样?

基本课程:在解析任何C++之前处理包含。它们由预编译器处理。

假设A.h最终在B.h之前被包括在内。你会得到这样的东西:

#ifndef A_H
#define A_H
// ----- B.h include -----    
#ifndef B_H
#define B_H
#include "A.h" // A_H is defined, so this does nothing
struct B {
int b;
};
void doStuff2 (A a);  // Error here
#endif
// ----- B.h include -----
struct A {
int a;
};
void doStuff1 (B b);  // Error here
#endif

此时,C++编译器可以接管并开始解析内容。它将尝试找出要doStuff2的参数是什么,但尚未定义A。同样的逻辑也适用于反之亦然。在这两种情况下,您都依赖于尚未定义的类型。

所有这些都只是意味着您的依赖项顺序不正常。这不是按值传递的问题。必须在使用方法之前定义类型。仅此而已 - 请参阅下面的示例。

// Example program
#include <iostream>
#include <string>
// data_types.h
struct A
{
int x;
};
struct B
{
int y;
};
using namespace std;
// methods_A.h
void foo(A a)
{
a.x = 3;
cout << "a: " << a.x << endl;
}
// methods_B.h
void bar(B b)
{
b.y = 4;
cout << "b: " << b.y << endl;
}
int main()
{
A first;
B second;
first.x = 0;
second.y = 100;
foo(first);
bar(second);
cout << "A: " << first.x << ", B: " << second.y << endl;
}

示例输出

a: 3
b: 4
A: 0, B: 100

你有一个循环包含。您需要将它们分成不同的头文件,例如让A.hB.h只声明结构/类,并让不同的头文件声明函数。

也可以通过使用前向声明并通过引用传递来解决此问题:

struct A;
struct B;
void doStuff1(A& a);
void doStuff2(B& b);