我正在制作国际象棋游戏,我想要一组棋子。
如果我是对的,在 Java 中你可以有一个抽象的 Piece
类,并让 King
或 Queen
扩展那个类。如果我要制作一个 Piece
数组,我可以在该数组中的某处放置一个 King
棋子,在另一个位置放置一个 Queen
棋子,因为两者King
和 Queen
扩展 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/