header 命名空间中的 C++ typedef 包含项找不到类型

标签 c++ types typedef typename

我有一个严格用于定义、全局数据、typedef 等的文件...

游戏数据.h

#include <utility>
#include "player.h"

namespace GameData {
    enum Color {
        BLACK = 0,
        WHITE = 1
    };
    typedef typename std::pair<char, int> Position;
    typedef typename std::pair< std::pair<char, int>, std::pair<char, int> > Move;
    typedef typename std::pair<Player*, Player*> Players;
};

我有两个问题:

(1) 未找到播放器类 - 尽管我已将其包含在 header 中

#include <string>
#include "board.h"
#include "gamedata.h"

class Player {
public:
    virtual ~Player() {}
    virtual Move getMove(Board &c) = 0;
};

(2)播放器头部的Move getMove函数无法解析Move

`Move` does not name a type 

我最好的猜测是发生这种情况是因为它是一个循环包含,两者都需要相互包含。

所以我在 gamedata.h 中转发声明 Player

class Player;
namespace GameData {
    enum Color {
        BLACK = 0,
        WHITE = 1
    };
    typedef typename std::pair<char, int> Position;
    typedef typename std::pair< std::pair<char, int>, std::pair<char, int> > Move;
    typedef typename std::pair<Player*, Player*> Players;
};

这解决了播放器问题,但现在移动仍然不稳定。

// None work
GameData::Move
Move

代码:

http://pastebin.com/i0GJz6xt

编辑 1

我想改变这个:

    typedef typename std::pair< std::pair<char, int>, std::pair<char, int> > Move;

    typedef typename std::pair<Position, Position> Move;

但我认为它产生了错误,所以我还没有将其还原。

最佳答案

好吧我在搜索 50 次后找到了答案哈哈。当我说我尝试转发声明 class Player 时,我没有删除问题所在的 #include "player.h"

引自 Peter 87:

You have a circular dependency. janitor.h includes lunch.h. lunch.h includes janitor.h, but the header guard prevents janitor.h from being included and lunch.h fails because it depends on what is in janitor.h.

To prevent this problem you can use forward declaration.

Instead of #include "janitor.h" you write class janitor; This will work as long as all you have is pointers or reference to janitor objects. If you use the object you will need to include the header so in the source files you will probably have to include them. Do the same with all your other headers, not just janitor.h. A good rule is to use forward declarations if it's enough and only include if you have to.

来源:http://www.cplusplus.com/forum/general/56475/

关于 header 命名空间中的 C++ typedef 包含项找不到类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21164882/

相关文章:

C++整数常量的类型

c++ - C++ 应该消除头文件吗?

python - Boost.Python 列出所有公开的类和属性

c++ - 为什么函数 GetOutlineTextMetrics() 对于不存在的字体名称返回 0?

c# - 如何求和两个对象?

c - 我应该在函数指针的 typedef 中保留 `_In_` 、 `_Out_` 之类的宏吗?

c++ - mingw "too many sections"错误,同时在 Qt 中编译巨大的头文件

类和协议(protocol)的 Swift Typealias

c - #define FOO 1u 2u 4u ... 1u 和 2u 是什么意思?

c - typedef 语句的不同命名方式的目的是什么?