我需要在不使用前向声明的情况下相互包含两个头文件,导致"incomplete type"错误

I need to include two header files to each other not using forward declaration cause get "incomplete type" error

本文关键字:包含两 文件 导致 错误 type incomplete 情况下 声明      更新时间:2023-10-16

我需要相互包含两个头文件,但我在执行此操作时遇到问题。除了使用前向声明和模板之外,还有什么方法可以做到这一点吗?或者我不允许用 c++ 做?

这是我想做的:

// A.hpp file
#ifndef H_A_H
#define H_A_H
#include "B.hpp"
class A {
private:
vector<B*> b;
public:
void function() {
// using methods of B
}
};
#endif

// B.hpp file
#ifndef H_B_H
#define H_B_H
#include "A.hpp"
class B {
private:
vector<A*> a;
public:
void function() {
// using methods of A
}
};
#endif

不能相互包含两个头文件。其中一个文件中应该有前向声明,并且必须将函数定义推送到.cpp文件中,您可以在其中包含头文件。

// HeaderA.h file
#ifndef H_A_H
#define H_A_H
#include "HeaderB.h"
class A {
private:
int b;
public:
void function() {
// using methods of B
B b;
b.function();
}
};
#endif
// HeaderB.h file
#ifndef H_B_H
#define H_B_H
class A;
class B {
private:
int a;
public:
void function();
};
#endif
// Main.cpp
#include "HeaderA.h"
#include "HeaderB.h"
void B::function()
{
// using methods of A
A a;
a.function();
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}

您有一个循环依赖关系。这个答案解释了如何通过前向声明来处理它们。

本文还讨论了循环依赖关系。

如果你100%不想使用前向声明,你可以在不同的类中拆分逻辑并使用组合。

// SomeLogic.h
class SomeLogic
{
};
// A.h
#include "SomeLogic.h"
class A
{
SomeLogic someLogic;
};
// B.h
#include "SomeLogic.h"
class B
{
SomeLogic someLogic;
};