繁体   English   中英

如果将对象创建为另一个 class 的数据成员,如何将值传递给参数化构造函数?

[英]How to pass value to parameterized constructors if there objects are being created as data members of another class?

我正在尝试使用 OOPS 概念在 C++ 制作国际象棋游戏,但遇到以下错误:

src/Game.cpp:6:36: error: no matching function for call to ‘Player::Player()’
 Game::Game(): player1(1), player2(0){
                                    ^
In file included from include/Game.h:4:0,
                 from src/Game.cpp:2:

这是我的代码:

播放器.h

#ifndef PLAYER_H
#define PLAYER_H
#include <string>
#include <King.h>
#include <Knight.h>
#include <Pawn.h>
#include <Queen.h>
#include <Bishop.h>
#include <Rook.h>
using namespace std;
class Player{
    public:
        Player(int color);
        void getMove();   
        int playerColor;             // 0 if player is black, 1 otherwise.   
    private:
        string move;                
        // each player has the following pieces.
        King king;                          
        Queen queen;
        Bishop bishop[2];
        Rook rook[2];
        Knight knight[2];
        Pawn paws[8];
};
#endif 

播放器.cpp

#include "Game.h"
#include "Player.h"
#include <string>
#include <iostream>
using namespace std;


Player::Player(int color)
:playerColor(color){
    
}

游戏.h

#ifndef GAME_H
#define GAME_H
#include <Pieces.h>
#include <Player.h>

class Game:public Player
{
    public:
        Game();
    private:
        Player player1;
        Player player2;
        Square cells[8][8];
        bool gameStatus;
        bool whiteTurn;
};

游戏.cpp

#include <iostream>
#include "Game.h"
#include "Pieces.h"
using namespace std;

Game::Game(): player1(1), player2(0){
    
}

在 Player.h 文件中创建各种片段对象时,我也遇到了类似的错误 如何创建这些对象?

错误的来源是Game派生自Player

Game::Game(): player1(1), player2(0){
}

是相同的

Game::Game(): Player(), player1(1), player2(0){
}

我的建议是不要让Player成为Game的基础 class。

// class Game : public Player
class Game
{
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM