c++ - C++ 中的抽象/基本结构?

标签 c++ class struct abstract-class structure

我正在制作国际象棋游戏,我想要一组棋子。

如果我是对的,在 Java 中你可以有一个抽象的 Piece 类,并让 KingQueen 扩展那个类。如果我要制作一个 Piece 数组,我可以在该数组中的某处放置一个 King 棋子,在另一个位置放置一个 Queen 棋子,因为两者KingQueen 扩展 Piece

有没有办法用 C++ 中的结构来做到这一点?

最佳答案

是的。您可以创建一个 abstract base class在 C++ 中。只需将一个或多个方法设置为纯虚拟:

class Piece {
    public:
        Piece ();
        virtual ~Piece ();
        virtual void SomeMethod () = 0;  // This method is not implemented in the base class, making it a pure virtual method. Subclasses must implement it
 };

然后您可以创建实现纯虚方法的子类

class King : public Piece {
    // ... the rest of the class definition
    virtual void SomeMethod (); // You need to actually implement this
};

关于c++ - C++ 中的抽象/基本结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9029548/

相关文章:

c++ - C++ 中的可移植高精度双时间戳?

c++ - STL 映射类数据结构,允许基于两个键进行搜索

java - 自定义 String 类创建

c - gcc 警告 "unnamed struct/union that defines no instances",但该结构确实有一个名称

C 中节俭的编码示例,使用文件

c++ - GLEW 只是扩展库还是包含 OpenGL ES 2.0 实现?

c++ - 派生值或附加属性的方法?

c++ - 如何声明包含整数数组的对象

c++ - 模板类和主要

c - 在c中插入单链表