C++ 类的构造函数与参数列表不匹配…但它与…匹配。。。。?
我正在制作一个国际象棋引擎并使用以下代码:C++ 类的构造函数与参数列表不匹配…但它与…匹配。。。。?,c++,game-engine,sfml,C++,Game Engine,Sfml,我正在制作一个国际象棋引擎并使用以下代码: #pragma once #include "SFML\Graphics.hpp" #include "Grid.h" enum PieceType { //place gamePieces into Grid not field, cus grid is already in field W_BISHOP, W_PAWN, W_KING, W_QUEEN,
#pragma once
#include "SFML\Graphics.hpp"
#include "Grid.h"
enum PieceType { //place gamePieces into Grid not field, cus grid is already in field
W_BISHOP,
W_PAWN,
W_KING,
W_QUEEN,
W_ROOK,
W_KNIGHT,
B_BISHOP,
B_PAWN,
B_KING,
B_QUEEN,
B_ROOK,
B_KNIGHT
};
class GamePieces //TODO PUT TEAM IN GRID, ACCESS GAME PIECES IN GRID TO MOVE THEM
{
public:
GamePieces(){}
GamePieces(PieceType& type, Coords& position) : m_type(type),m_position(position) {
switch (type) {
case W_BISHOP:
m_gamePiece.loadFromFile("w_bishop");
m_gamePieceSprite.setTexture(m_gamePiece);
break;
//REST OF CASES OF PIECETYPE ARE PRETTY MUCH THE SAME
}
~GamePieces();
private:
sf::Texture m_gamePiece;
sf::Sprite m_gamePieceSprite;
Coords m_position;
PieceType m_type;
};
enum TeamColor {
BLACK,
WHITE
};
struct Team {
//16 pieces in regular chess
//map that assigns specific game pieces coordinates
GamePieces m_chessPieces[16];
TeamColor color;
Team() {}
Team(TeamColor& c) {
Coords coord;
switch (c) {
case WHITE:
for (int i = 0; i < 8; i++) {
coord.m_x += 52.5;
coord.m_y += 52.5;
m_chessPieces[i] = GamePieces(PieceType::B_PAWN, coord);
}
break;
它说
GamePieces
的构造函数没有指定的参数列表,但它有 临时无法绑定到非常量引用,请将构造函数更改为
GamePieces(const PieceType& type, const Coords& position)
GamePieces(const PieceType& type, const Coords& position)
或
构造函数通过非常量引用获取其参数,没有任何原因 非常量引用不能绑定到常量,例如
PieceType::B_PAWN
除非要修改被调用函数中的参数,否则应按值传递枚举。您应该通过常量引用传递结构,例如
Coord
,或者如果它们足够小和简单,则有时通过值传递(但通过常量引用是一个安全的回退选项)。这是因为您试图将右值(PieceType::B_PAWN
)分配给非常量引用。语言不允许您这样做
解决方案是使构造函数按值或常量引用获取:
GamePieces(PieceType type, const Coords& position) //...
你的功能似乎是错误的。删除引用:
GamePieces(PieceType type, Coords position)
更新:
请注意,上面这一行是解决问题的最简单方法。正如前面的评论所说,您可以通过值或常量引用获取参数
在本例中,第一个是非常小的对象,因此您可以按值获取它。第二个可以由cont引用,因为它可能更大(8字节?)。从这个意义上说,@TartanLlama的答案是完美的
尽管如此,按值同时使用这两种方法是一个很好的解决方案,因为您的方法是内联的,编译器有机会优化代码(例如,使用寄存器而不是堆栈来传递参数)。语法:
GamePieces(PieceType::B_PAWN, coord);
这是不对的。对于enum
变量,不必声明枚举类型。正确的语法如下所示:
GamePieces(B_PAWN, coord);
宣言:
GamePieces(PieceType& type, Coords& position)
不正确,因为您使用了非常量引用。您必须将其更改为以下内容:
GamePieces(B_PAWN, coord);
GamePieces(const PieceType& type, const Coords& position)