[英]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.