C++:相互包含头文件

C++: Including header files in each other

本文关键字:包含头 文件 C++      更新时间:2023-10-16

所以我看到了这个问题,但人们提供的例子非常简单(他们的类没有构造函数或方法(,我不知道如何将解决方案扩展到更复杂的情况。

我尝试过使用正向声明和指针,只是正向声明,只是指针,甚至是正向声明和类型名定义,所有这些都是其他更简单的帖子中建议的解决方案,但都不起作用(未知标识符或不完整的类型错误(。那么,我该如何使下面的两个文件正确编译并按我的意图使用呢?

单位.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;}