我经常发现自己处于一种情况,我在C++项目中面临多个编译/链接器错误,因为一些糟糕的设计决策(由其他人做出:))导致不同头文件中C++类之间的循环依赖(也可能发生)在同一个文件中).但幸运的是(?)这种情况经常不足以让我在下次再次发生问题时记住这个问题的解决方案.
因此,为了便于将来回忆,我将发布一个代表性问题和解决方案.更好的解决方案当然是受欢迎的.
A.h
class B;
class A
{
int _val;
B *_b;
public:
A(int val)
:_val(val)
{
}
void SetB(B *b)
{
_b = b;
_b->Print(); // COMPILER ERROR: C2027: use of undefined type 'B'
}
void Print()
{
cout<<"Type:A val="<<_val<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)B.h
#include "A.h"
class B
{
double _val;
A* _a;
public:
B(double val)
:_val(val)
{
}
void SetA(A *a)
{
_a = a;
_a->Print();
}
void Print()
{
cout<<"Type:B val="<<_val<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)main.cpp
#include "B.h" …Run Code Online (Sandbox Code Playgroud)在:http://www.learncpp.com/cpp-tutorial/19-header-files/
提到以下内容:
add.cpp:
int add(int x, int y)
{
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中:
#include <iostream>
int add(int x, int y); // forward declaration using function prototype
int main()
{
using namespace std;
cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我们使用了前向声明,以便编译器在编译时知道"
add"是什么main.cpp.如前所述,为要在其他文件中使用的每个函数编写前向声明可能会很快变得乏味.
你能进一步解释" 前瞻性宣言 "吗?如果我们在main()函数中使用它会有什么问题?