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

Why can't header files include eachother?

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

A.h:

#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' 也一样。 我知道前向声明,但我想看看是否可以将这样的设置设置为按值传递而不是 reference/pointer。如果 AB 实际上在编译器到达该代码时已声明,为什么编译器会这样?

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

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

struct A;
struct B;

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

基本课程:在解析任何 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