覆盖受保护的变量 C++

ada*_*yle 1 c++ oop

假设我有以下代码:

class Board
{
  protected:
    std::vector<Piece*> pieces;
}

class ChessBoard : public Board
{
  protected:
    std::vector<ChessPiece*> pieces;

}
Run Code Online (Sandbox Code Playgroud)

我希望派生类pieces用这个 new覆盖受保护的变量vector,但是我遇到了困难,而且这似乎是不好的做法。

eer*_*ika 5

没有“覆盖变量”这样的东西,无论是受保护的还是其他方式。

在您的示例程序中,类ChessBoard包含一个成员的子对象pieces和底座子对象Board包含该构件Board::pieces。因此,对象内部有两个向量。

面向对象编程是通过虚函数实现的。你还没有解释你想要做什么(除了一些无法完成的事情)所以这只是一个猜测,但也许你正在寻找协变返回类型:

class Board
{
    protected:
        virtual Piece&
        operator[](std::size_t index) = 0;

    public:
        virtual ~Board() = default;
};

class ChessBoard : public Board
{
    std::vector<ChessPiece> pieces;

    protected:
        virtual ChessPiece&
        operator[](std::size_t index) override;
};
Run Code Online (Sandbox Code Playgroud)

此外,如果子类除了类型之外具有相同的基函数和/或成员函数实现,那么您可以通过使用模板来避免重复。