[英]C++: Including header files in each other
因此,我已经看到了这个问题,但是人们提供的示例非常简单(它们的类没有构造函数或方法),而且我不知道如何将解决方案扩展到更复杂的情况。
我尝试过使用前向声明和指针,仅使用前向声明,仅使用指针,甚至使用前向声明和类型名定义,所有这些都是其他较简单文章的建议解决方案,但均无用(未知标识符或不完整的类型错误)。 那么,如何获得下面的两个文件以正确进行编译并按预期使用?
Unit.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
您需要前向声明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;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.