C++:相互包含头文件
C++: Including header files in each other
所以我看到了这个问题,但人们提供的例子非常简单(他们的类没有构造函数或方法(,我不知道如何将解决方案扩展到更复杂的情况。
我尝试过使用正向声明和指针,只是正向声明,只是指针,甚至是正向声明和类型名定义,所有这些都是其他更简单的帖子中建议的解决方案,但都不起作用(未知标识符或不完整的类型错误(。那么,我该如何使下面的两个文件正确编译并按我的意图使用呢?
单位.hpp:
#ifndef PROJECT_UNIT_HPP
#define PROJECT_UNIT_HPP
#include "GridNode.hpp"
class Unit
{
private:
/* Fields */
int xPos, yPos, ownerID;
std::vector<GridNode> influenceMap;
public:
/* Constructors */
Unit(int x, int y, int id) : xPos(x), yPos(y), ownerID(id)
{
influenceMap.push_back( GridNode() );
}
/* Methods */
std::vector<GridNode> getMap() {return influenceMap;}
};
#endif
GridNode.hpp:
#ifndef PROJECT_GRIDNODE_HPP
#define PROJECT_GRIDNODE_HPP
#include "Unit.hpp"
class GridNode
{
private:
/* Members */
int id;
std::vector<Unit> nodeUnits;
public:
/* Static vars */
static int nodeLength;
/* Constructors */
GridNode()
{
std::cout << "Reached here!n";
}
};
#endif
您只需要在两者中都声明#include <vector>
,并在GridNode.hpp
:中转发声明class Unit;
#ifndef PROJECT_GRIDNODE_HPP
#define PROJECT_GRIDNODE_HPP
// using std::vector
#include <vector>
// Forward declare
class Unit;
class GridNode
{
private:
/* Members */
int id;
std::vector<Unit> nodeUnits;
public:
/* Static vars */
static int nodeLength;
/* Constructors */
GridNode()
{
std::cout << "Reached here!n";
}
};
#endif
您需要前向声明AND来将成员函数体(包括构造函数和析构函数(移出类体,并在包含其他类定义之后。
即使是隐式构造函数和析构函数也会破坏事物,您也需要显式的用户提供声明(尽管您可以通过= default
使用编译器提供的定义(
class GridNode;
class Unit
{
private:
/* Fields */
int xPos, yPos, ownerID;
std::vector<GridNode> influenceMap;
public:
/* Constructors */
Unit(int x, int y, int id);
Unit(const Unit&);
~Unit();
/* Methods */
std::vector<GridNode> getMap();
};
#include "GridNode.hpp"
inline Unit::Unit(int x, int y, int id) : xPos(x), yPos(y), ownerID(id)
{
influenceMap.push_back( GridNode() );
}
inline Unit::Unit(const Unit&) = default;
inline Unit::~Unit() = default;
inline std::vector<GridNode> Unit::getMap() {return influenceMap;}
相关文章:
- 使用mongocxx驱动程序时包含头文件问题
- 如何为包含头文件的目标编写生成文件?
- 如何在 CMakeLists.txt Qt Creator 中包含头文件?
- 当包含头文件的文件不在根项目文件夹中时,如何包含它
- 在生成文件先决条件中包含头文件的原因
- My Project的属性配置正确,但Visual Studio仍然无法打开包含头文件
- 在 PostgreSQL C 扩展中包含头文件
- 是否可以在C++中以间接方式包含头文件
- 是否需要包含头文件?
- 我收到未声明的标识符错误,但我已包含头文件?
- 为什么我们需要构建一个提升库,仅仅包含头文件还不够吗,因为提升是模板
- C++:当顺序真正重要时,如何保证在项目中包含头文件的顺序
- 如何在C++中包含头文件时错误地重载
- 我在C++中无效使用不完整的类型类错误,如何正确包含头文件?
- 虚幻引擎4.16,C++包含头文件
- C++多次包含头文件
- 令牌之前的预期类名 '{' - 包含头文件和 CPP 文件
- 在.cpp中包含头文件会导致令人讨厌的错误
- 如何列出用于在Qt项目中包含头文件的所有路径
- 尽管包含头文件,但仍找不到嵌套命名空间