C++:相互包含头文件

标签 c++ header-files

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

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

单位.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/

相关文章:

枚举类的 c++ typedef/type 替换

c++ - 为什么我不应该将 "using namespace std"放在标题中?

c - 如何在原型(prototype)中调用带有 __P 的函数?

c++ - svcutil/l :CPP/out: output_Folder_Path wsdl_folder_path? 的输出是什么

c++ - xstring 中未定义的类型和未声明的标识符

c++ - 如何新建一个 string[] ?

c++ - 你如何为visual studio 2008 sp1设置环境变量?

c++ - 我可以插入移动的容器吗

c++ - std::function const 正确性

c++ - 合并头文件和cpp文件