为什么头文件不能相互包含?
Why can't header files include eachother?
为什么我不能在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'
也是如此. 我知道前向声明,但我想看看是否有可能将这样的设置作为按值传递而不是通过引用/指针。如果编译器到达该代码时实际上已声明A
和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
你有一个循环包含。您需要将它们分成不同的头文件,例如让A.h
和B.h
只声明结构/类,并让不同的头文件声明函数。
也可以通过使用前向声明并通过引用传递来解决此问题:
struct A;
struct B;
void doStuff1(A& a);
void doStuff2(B& b);
相关文章:
- 不能包含<cwindows>
- 为什么头文件不能相互包含?
- 不能包含"vcruntime_new_debug.h"
- 不能在其他文件中包含结构
- 我的项目中某些仅标头文件不能包含使用 CMake 和 Vscode 的"SFML/Graphics.hpp"
- 不能包含 cliext 标头(对于 c++ cli、Visual Studio)
- 为什么 UInt64 变量不能包含大于 UInt32::Max 的值?
- 为什么我不能创建包含 vec3 对象的联合?
- C++11 向量包含 2 个不同的子类,但不能同时进行
- 不能包含<QtWidgets>
- Cmake 不能包含来自主的升压库
- 不能在 OS X 上包含 opencv3
- 不能使用包含 math.h 和 g++ 7 (Raspberry PI) 的 C 库
- 不能包含为 <QtCore/QString>
- 不能在 c++ 中的字符串中包含整数
- 不能在 dlib cpp 文件中包含JPEG_SUPPORT标头
- 无法使用名称空间,也不能在我的.h文件中包含标准的C 库
- python永远不能调用包含继承逻辑的c++dll或左右文件
- 为什么ShellExecute不能使用包含文件路径的LPCSTR变量
- 不能包含 d3dx9.h C++