【问题标题】:C++ Why Is There "Unknown Type" When Class Header is Included? [duplicate]C ++为什么包含类头时会出现“未知类型”? [复制]
【发布时间】:2016-08-30 15:45:42
【问题描述】:

我有这个头文件,我正在尝试创建Item 类型的变量。我已经包含了#include "Item.h",但在编译时我仍然在两个私有变量上收到unknown type name 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 */

这是怎么回事?

这是我所包含的Item.h

#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 */

【问题讨论】:

  • 注意:类体内定义的方法是自动内联的,所以GetValue 上的inline 关键字是多余的。将 0 参数参数列表标记为 void 也是多余的。
  • 在代码的顶部,您已经编写了“使用 std::vector”。用“std::”声明向量不是没必要吗?

标签: c++


【解决方案1】:

如果您从cpp 文件中包含Item.h,则其中包含Player.h。然后,Player.h 再次包含Item.h,但是由于包含保护,这几乎没有任何作用。

那么,在包含的Player.h 中,还没有声明Item。因此,编译器会发出错误。

由于Item.h 中没有使用来自Player.h 的任何内容,请从Item.h 中删除#include "Player.h"

【讨论】:

  • 如果Item.h 确实需要#include "Player.h" 怎么办?
  • 修改设计以消除循环依赖。
  • 我的意思是问一个人会怎么做。如果Item 需要接受Player 类型作为参数,你怎么能不重新引入循环依赖呢?
  • 使用声明class Player;并使用引用作为参数。
【解决方案2】:

您将"Player.h" 包含在"Item.h" 中,并使其成为circular dependency。由于根本不需要,所以只需将其删除即可。

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2017-07-11
    • 2010-09-23
    相关资源
    最近更新 更多