我需要在不使用前向声明的情况下相互包含两个头文件,导致"incomplete type"错误
I need to include two header files to each other not using forward declaration cause get "incomplete type" error
我需要相互包含两个头文件,但我在执行此操作时遇到问题。除了使用前向声明和模板之外,还有什么方法可以做到这一点吗?或者我不允许用 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;
};
相关文章:
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 如何在for循环中包含两个索引值的测试条件
- 包含模板文件的递归会导致编译失败
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 在C++中包含原型文件的正确方法是什么?
- 包含在.cpp文件中包含在 .h 文件时包含
- 如何为包含头文件的目标编写生成文件?
- 使用提升元解析字符串解析包含的文件
- 在头文件上包含 cpp 文件是否有缺点?
- 我需要在不使用前向声明的情况下相互包含两个头文件,导致"incomplete type"错误
- 如何使用预处理器指令包含两次具有不同代码的文件?
- 包含两个C++文件的制作文件:如何选择要编译的文件
- 尽管 #ifndef,但包含两次头文件
- NetBeans - 两个项目 - 一个找不到要包含的文件 (C++)
- C++:创建一个包含两个可执行文件的makefile?C++
- 错误LNK2005:已经定义了包含头文件两次
- c++讨厌在文件中包含两种或两种以上的数据类型
- 为什么同一个头文件必须包含两次?
- 为包含两个类的头文件构建C++文件