如何使用抽象对象数组?无效的抽象类型错误

Cay*_*ira 1 c++ oop abstract

我正在用C ++编写国际象棋游戏,而Player具有16个棋子的数组,这是每个棋子(马,兵,国王等)的抽象类。编译器给我一个“ pecas”无效的抽象类型“ Peca”。我在做什么错?谢谢!

播放器

#include "Peca.h" // Includes Piece abstract class

using std::string;

class Jogador
{
    private:
        static int numeroDeJogador; //PlayerNumber (0-1)
        string nome;
        Peca pecas[16]; //This is the array of the abstract class Pecas (Pieces), where i want to put derived objects like Horse, king..

    public:
        string getNomeJogador(); // Return the player name

};
Run Code Online (Sandbox Code Playgroud)

件数

#ifndef PECA_H
#define PECA_H
#include <string>

using std::string;

class Peca {

    private:
        int cor; //0 para as brancas, 1 para as pretas
        bool emJogo;

    public:
        Peca(int cor);
        virtual string desenha() = 0;
        virtual bool checaMovimento(int linhaOrigem, int colunaOrigem, int linhaDestino, int colunaDestino) = 0;
        int getCor();
        bool estaEmJogo();
        void setForaDeJogo(bool estado);
};
#endif
Run Code Online (Sandbox Code Playgroud)

派生类示例:

#include "Peca.h"

using std::string;

class Cavalo : public Peca {
    public:
        Cavalo(int cor);
        bool checaMovimento(int linhaOrigem, int colunaOrigem, int linhaDestino, int colunaDestino);
        string desenha();
};
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 6

数组要求数组的对象是可构造的。您不能构造一个,Peca所以不能包含它们的数组。

您需要的是指向的指针容器Peca。指针始终是可构造的,即使它们不能指向。在这种情况下,您可以使用a,std::array<std::unique_ptr<Peca>, 16> pecas以便您拥有一个托管指针数组。