如何创建一个继承自std :: vector的类

时间:2018-05-03 18:58:23

标签: c++ class c++11 inheritance stdvector

我需要继承std::vector的所有函数,并且我想重载运算符来创建一个完整的matrix类。 关于这个主题没有太多的文档。

Matriz.h

#include <vector>
#include <iostream>
using namespace std;

template<typename T>
class Matriz:vector<T>
{
public:
    using vector<T>::vector;
private:
}

Matriz.cpp

int main()
{
    Matriz<int> dani;
    dani.push_back(2); //Here is the error and I don`t know what it happens
}

当我想初始化它时,我收到了一个错误。

Severity    Code    Description Project File    Line    Suppression State
Error   C2247   'std::vector<int,std::allocator<_Ty>>::push_back' not accessible because 'Matriz<int>' uses 'private' to inherit from 'std::vector<int,std::allocator<_Ty>>'

1 个答案:

答案 0 :(得分:0)

这应该有效:

#include <vector>
#include <iostream>

template<typename T>
class Matriz: public std::vector<T>
{
public:
   using std::vector<T>::vector;

private:
};

int main()
{
   Matriz<int> dani;
   dani.push_back(2);
   dani.push_back(3);

   for(const auto& it: dani)
      std::cout << it << " ";
}