【问题标题】:C++ Compiler Error; Namespace issue I guessC++ 编译器错误;我猜命名空间问题
【发布时间】:2012-01-15 00:59:06
【问题描述】:

我得到的错误是“命名空间 ChessGame 中没有名为 detail 的成员。这是相关代码

//ChessPiece.h
namespace ChessGame 
{

class ChessBoard;

namespace detail
{
    class IChessPieceEnums{
    public:
        enum PieceType{PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING};
        enum PieceDirection{ UP = 1 , DOWN  = -1};
        enum PieceId{ WHITE_PIECE_ID, BLACK_PIECE_ID };
    };
}

//represents an abstract chess piece interface
class IChessPiece : public detail::IChessPieceEnums
{
public:   
 ///...
}

} // end namespace


//GameBoard.h
#include "ChessPiece.h"
namespace ChessGame 
{

 class IChessPiece;

 class ChessBoard
 {
  public:
    /*********ERROR OCCURS ON THIS FUNCTION************/
    bool isOccupiedWithEnemy(int row, int col,const ChessGame::detail::IChessPieceEnums::PieceId& pieceId);
 }
}

有什么想法吗?

编辑:另一个最小的例子:

//Piece.h

#ifndef TestProject_C___Piece_h
#define TestProject_C___Piece_h

#include "Board.h"

namespace Foo {
namespace detail{
    struct PieceEnums{
        enum PieceID{ ID1, ID2 };
    };
}

class Board;

class Piece{
public:
    void foo(Board& b)const;
};
}
#endif

//board.h

 #ifndef TestProject_C___Board_h
 #define TestProject_C___Board_h

 #include "Piece.h"


namespace Foo {
class Piece;

class Board{
    bool isOcc(int x, int y,const detail::PieceEnums::PieceID pid)const;
};
}

#endif

错误是“使用未声明的标识符详细信息”

请注意,这是跨多个文件的,所以可能是链接问题?

【问题讨论】:

  • 修复语法错误,编译正常。
  • 为什么pieceId是参考?您是否有机会使用文字 PieceId 调用 osOccupiedWithEnemy?
  • @pezcode:是的,我猜它不需要。我将通过给它一个位置(x,y)和一个文字 PieceId 来调用它,是的

标签: c++ namespaces compiler-errors


【解决方案1】:

要直接指定所需的名称,请说detail::IChessPieceEnums::PieceId::ChessGame::detail::IChessPieceEnums::PieceId,但最好是前者。但是,您当前的语法实际上也很好,因为如果找不到名称,搜索将在全局命名空间中恢复。

【讨论】:

  • 我都试过了,得到了同样的错误。由于某种原因,它没有找到“详细”命名空间
  • 您修复了语法错误吗?您需要在类定义的末尾使用分号。
  • 是的,就是上面帖子里的类型
  • @user814628:那么请发布一个真实的、最小的示例。尝试将其缩减为最小的代码段,否则它是正确的并且只有这个问题。到目前为止,我无法重现它,您的错误在其他地方。
【解决方案2】:

好的,找到了解决方案。解决方案是将命名空间详细信息放在其自己的名为 detail.h 的文件中。这样,piece.h 和 board.h 需要包含 details.h 才能使用它。那行得通。

而原帖的问题在于存在循环引用。这在某种程度上造成了麻烦。希望得到解释。

【讨论】:

  • 哦,问题是我在 board.h 之前包含了piece.h,我需要切换它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 2017-12-16
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
相关资源
最近更新 更多