如何继承 C++ STL 容器?

2023-04-21 阅读 77

在 C++ STL 中,容器是通过模板类实现的,因此我们可以通过继承模板类来继承 STL 容器。具体步骤如下:

  1. 确定你要继承哪个 STL 容器,比如 vector。

  2. 创建一个新的类,并继承 STL 容器,比如:

template <typename t="">
class MyVector : public std::vector<t> {
    // ...
};
  1. 在新类中添加你想要的成员函数和成员变量。

  2. 在构造函数中调用 STL 容器的构造函数:

template <typename t="">
class MyVector : public std::vector<t> {
public:
    MyVector() : std::vector<t>() {
        // ...
    }
    // ...
};
  1. 如果需要重载 STL 容器的成员函数,可以使用 using 关键字:
template <typename t="">
class MyVector : public std::vector<t> {
public:
    using std::vector<t>::push_back;
    void push_back(const T&amp; t) {
        // ...
    }
    // ...
};

这样,我们就可以使用 MyVector 类来代替 vector 类,并且可以使用 MyVector 类中新增的成员函数和成员变量。

更新于 2023年04月24日