我经常发现自己处于一种情况,我在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)我无法解决这个循环依赖问题; 总是得到这个错误:"无效使用不完整类型结构GemsGame"我不知道为什么编译器不知道GemsGame的声明,即使我包含gemsgame.h两个类都相互依赖(GemsGame存储GemElements的向量) ,和GemElements需要访问这个相同的向量)
这是GEMELEMENT.H的部分代码:
#ifndef GEMELEMENT_H_INCLUDED
#define GEMELEMENT_H_INCLUDED
#include "GemsGame.h"
class GemsGame;
class GemElement {
private:
GemsGame* _gemsGame;
public:
GemElement{
_gemsGame = application.getCurrentGame();
_gemsGame->getGemsVector();
}
};
#endif // GEMELEMENT_H_INCLUDED
Run Code Online (Sandbox Code Playgroud)
......和GEMSGAME.H:
#ifndef GEMSGAME_H_INCLUDED
#define GEMSGAME_H_INCLUDED
#include "GemElement.h"
class GemsGame {
private:
vector< vector<GemElement*> > _gemsVector;
public:
GemsGame() {
...
}
vector< vector<GemElement*> > getGemsVector() {
return _gemsVector;
}
}
#endif // GEMSGAME_H_INCLUDED
Run Code Online (Sandbox Code Playgroud)