首页 > 解决方案 > 常量 X 不是类型名称,这里 x 是 KING

问题描述

我在传递给 Piece 构造函数的 KING 和 COLOR 参数上遇到错误。这是我的代码,我正在制作一个带有 main 类的国际象棋游戏,然后 tehre 是一个游戏类,它制作一个棋盘对象,棋盘玩游戏,并将正方形和棋子作为组件对象。他们都在建立关联关系

 /////////////////////////PIECE HEADER///////////////////
enum PIECETYPE { KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN };
enum COLOR { BLACK, WHITE };
class Square;//forward declaration

class Piece
{
    PIECETYPE type;
    COLOR color;
    ...};
/////////////////////PIECE CPP////////////////////////

#include "Piece.h"
#include"Square.h"



Piece::Piece()
{
}
Piece::Piece(PIECETYPE typ, COLOR clr){
    type = typ;
    color = clr;
    pSquare = nullptr;
}
//////////////////////BOARD HEADER: COMPOUNDCLASS////////////////////////
#include"Piece.h"``


class Board
{
    Square square[8][8];
    Piece wK(KING, WHITE);
    Piece bK(KING, BLACK);};

标签: c++oopenums

解决方案


声明类的成员变量时不能使用该构造函数语法。编译器不知道您是否尝试使用 namewK和 return type声明成员函数Piece,在这种情况下KING应该是第一个参数的类型。

class Board {
    Piece wK(KING, WHITE);  // ERROR: this is declaring wK and using its constructor in ambigous way.
    ...
};

这是这样做的方法:

class Board {
    Piece wK;  // declaring the member wK
    Board() : wk(KING, WHITE) {}  // initialize wK in the Board constructor
    ...
};

或者,在 C++11 中

class Board {
    Piece wK{KING, WHITE};  // Using {} instead of () makes it clear you are not declaring a function
    ...
};

推荐阅读