C++ C++;“为什么会有?”;“未知类型”;何时包含类标题?
我有这个头文件,我正在尝试创建C++ C++;“为什么会有?”;“未知类型”;何时包含类标题?,c++,C++,我有这个头文件,我正在尝试创建Item类型的变量。我已经包含了#include“Item.h”,但在编译时,两个私有变量上都出现了未知类型名Item错误 #ifndef PLAYER_H #define PLAYER_H #include <vector> #include "Item.h" using std::vector; class Player { public: // constructor Player( void ); // d
Item
类型的变量。我已经包含了#include“Item.h”
,但在编译时,两个私有变量上都出现了未知类型名Item
错误
#ifndef PLAYER_H
#define PLAYER_H
#include <vector>
#include "Item.h"
using std::vector;
class Player
{
public:
// constructor
Player( void );
// destructor
virtual ~Player( void );
private:
Item item;
std::vector <Item> inventory;
};
#endif /* PLAYER_H */
如果从
cpp
文件中包括Item.h
,则从中包括Player.h
。然后,Player.h
再次包含Item.h
,但多亏了include守卫,这实际上什么也没做
然后,在包含的Player.h
中,尚未声明任何项。因此,编译器将发出错误
由于Player.h
中没有任何内容用于Item.h
,因此从Item.h
中删除#包括中的“Player.h”
,您将中的“Player.h”
包括在Item.h
中。因为根本不需要,所以只需删除它。注意:在类主体中定义的方法是自动内联的,因此GetValue
上的inline
关键字是多余的。另外,将0参数参数列表标记为void
也是多余的。如果Item.h
确实需要#包含“Player.h”
?修改设计以消除循环依赖性,是否没有必要声明一个带有“std::”的向量?我想问的是如何做到这一点。如果Item
需要接受Player
类型作为参数,您如何在不重新引入循环依赖项的情况下实现这一点?使用声明类Player代码>并使用引用作为参数。
#ifndef ITEM_H
#define ITEM_H
#include <string>
#include "Player.h"
#include "GlobalDefs.h"
class Item {
public:
Item();
Item(gold_t v, std::string n);
virtual ~Item();
// Getter
inline virtual gold_t GetValue (void)
{
return value;
}
// Getter
inline virtual std::string GetName (void);
// Getter
virtual std::string GetItemText(void);
protected:
gold_t value;
std::string name;
};
#endif /* ITEM_H */