所以我看到有人提出这个问题,但是人们提供的示例非常简单(他们的类没有构造函数或方法),我不知道如何将解决方案扩展到更复杂的情况。
我尝试过使用前向声明和指针,仅前向声明,仅指针,甚至前向声明和类型名定义,所有这些都是其他更简单的帖子中建议的解决方案,但没有一个起作用(未知标识符或不完整类型)错误)。那么我如何才能正确编译下面的两个文件并按我的预期使用呢?
单位.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>
在两者和前向声明 class Unit;
在GridNode.hpp
:
#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
关于C++:相互包含头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31214753/