c++ - 常量 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);};
解决方案
声明类的成员变量时不能使用该构造函数语法。编译器不知道您是否尝试使用 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
...
};
推荐阅读
- c++ - 是否必须初始化成员才能获取其地址?
- bash - 无法在 solaris 中使用 find 语句执行命令
- r - 变量中的正则表达式,如何处理特殊字符?
- selenium - 使用katalon执行自动测试时jenkins中的意外作业中止
- reactjs - 如何在 React 中导入 Snipcart?
- regex - 如何更改文本文件中的值?
- mlr - 在具有主题 ID 的 mlr 中阻止交叉验证
- python - 在会话中保存函数结果导致 TypeError 对象不可 JSON 序列化
- typescript - 有时可能未定义的 Typescript 泛型参数的模式?
- java - 为什么我会收到此错误:E/ERROR:executeQuery 方法必须返回结果集。?