我遇到这种情况:
class GEngine {
private:
ChessBoard board;
ChessMoves checkBoard(board);
...
和ChessMoves c'tor定义如下:
class ChessMoves {
private:
ChessBoard nullChessBoard;
ChessBoard const& refBoard;
Flags cBoard[8][8]; //checkboard
public:
ChessMoves():refBoard(nullChessBoard){resetcBoard();}
ChessMoves(ChessBoard const& ref):refBoard(ref){resetcBoard();};
但它会返回此错误:
GameEngine.cpp:250: error: ‘((GEngine*)this)->GEngine::checkBoard’ does not have class type
GameEngine.cpp:251: error: ‘((GEngine*)this)->GEngine::checkBoard’ does not have class type
GameEngine.cpp:251: error: ‘((GEngine*)this)->GEngine::checkBoard’ does not have class type
当我运行此代码时:
//check if piece can move there
checkBoard.fillcBoard(from); //checkBoard called here...
if(checkBoard.get(to) == canPASS or checkBoard.get(to) == canEAT){
/*empty*/
}
else{
return isValid = false;
}
return isValid = true;
我想作为对其他类的引用传递,初始化是成员:
类似
class X{
private:
ref const& _Mreference;
public:
X( ref const& ref):_Mreference(ref){}
};
有可能吗?
答案 0 :(得分:3)
当你这样做时
ChessMoves checkBoard(board);
您在类范围GEngine
内声明了一个函数。这也是一个无效的声明(因为board不是一个类型 - 查找来自编译器的其他错误消息)。当你做
checkBoard.fillcBoard(from);
你的编译器认为你访问声明函数的成员函数是什么,这是非法的,因为GEngine::checkBoard
不是类类型(而是函数类型,这就是编译器所说的)。
你想要做的是:
class GEngine {
private:
ChessBoard board;
ChessMoves checkBoard;
...
// In the implementation file
GEngine::GEngine() : board(), checkBoard(board) {}
它应该没问题。只是要确保你(在这种情况下)永远不会改变类中的声明顺序,因为类成员按其声明的顺序初始化(但是如果你把它混合起来,你的编译器应该警告你 - 确保严肃对待这个警告。)
答案 1 :(得分:1)
您的支票声明无效。你不能像这样初始化类中的对象(至少在C ++ 03中没有,并且我知道没有编译器支持C ++ 11特性)。您需要在构造函数中执行此操作,如下所示:
class GEngine {
private:
ChessBoard board;
ChessMoves checkBoard;
public:
GEngine()
:checkBoard(board)
{}
};