简体   繁体   English

抽象类中的C ++ equal方法

[英]C++ equal method in an abstract class

I'm developing a chess game. 我正在开发国际象棋游戏。 So, I created an abstract class called Piece and the real pieces implement this class, So I have concrete classes like Pawn, Rook... 因此,我创建了一个称为Piece的抽象类,而真正的件实现了该类,所以我有Pawn,Rook等具体类。

The problem is: I need an equal method in the interface to compare two pieces. 问题是:我需要在接口中使用相等的方法来比较两部分。 I'm having problem to it, because I wanted a polimorfic method, that is, a method that could compare a piece to any piece. 我遇到了问题,因为我想要一种策略方法,即一种可以将一个工件与任何工件进行比较的方法。 The problem is I can't declare "Piece o" as an argument to the method cause Piece is an abstract type. 问题是我无法将“ Piece o”声明为方法的参数,因为Piece是抽象类型。 How can I do this in C++? 如何在C ++中做到这一点?

I have the following code: 我有以下代码:

class Piece
{
public:
    virtual ~Piece();

    virtual std::string name() = 0;
    virtual Color color() const = 0;
    virtual Type type() const = 0;
    virtual Position position() const = 0;
    virtual void moveToPosition(Position p) = 0;
    virtual bool isValidMove(Position np, Board &b) = 0;
    virtual vector<Movimento>& generateMoves(Board &t) = 0;
    virtual bool equal(Piece &o) = 0;
};

maybe do something like 也许做类似的事情

virtual bool operator==(const Piece&) = 0;

no object slicing, u can compare the type and other information.. 没有对象切片,您可以比较类型和其他信息。

or you can just implement it in your Piece class, such as 或者您也可以在Piece类中实现它,例如

virtual bool operator==(const Piece& rhs) {
    if (this.type() == rhs.type()) {
        return true;
    }
    else {
        return false;
    }
}

actually, you probably don't need operator== overloaded, but instead just a equal method... 实际上,您可能不需要operator==重载,而只是一个equal方法...

I solved my problem changing the defition of Piece to an Abstract class instead of a Interface (in the Java vocabulary). 我解决了将Piece的定义更改为Abstract类而不是Interface(在Java词汇表中)的问题。 Now my code is less redundant and clearer. 现在,我的代码减少了冗余,变得更加清晰。

class Piece
{
protected:
    std::string m_Name;
    Color m_Color;
    PieceType m_PieceType;
    Position m_Position;

public:
    Piece(std::string n, Color c, PieceType t, Position p) :
          m_Name(n), m_Color(c), m_PieceType(t), m_Position(p){};
    virtual ~Piece();

    std::string name() const;
    Color color() const;
    PieceType pieceType() const;
    Position position() const;
    bool equal(const Piece&) const;
    virtual void moveToPosition(Position p) = 0;
    virtual bool isValidMove(Position np, Board &t) = 0;
    virtual vector<Move>& generateMoves(Board *b) = 0;
};

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

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