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

How to create a class which inheritates from std::vector

本文关键字:std vector 的类 继承 何创建 创建 一个      更新时间:2023-10-16

我需要从std::vector继承所有函数,我想重载运算符以创建一个完整的matrix类。 关于此主题的文档不多。

马特里兹·

#include <vector>
#include <iostream>
using namespace std;
template<typename T>
class Matriz:vector<T>
{
public:
using vector<T>::vector;
private:
}

马特里兹.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>>'

这应该有效:

#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 << " ";
}

从向量类继承是一个错误

正如这里所说,这是非常困难的,并且会产生很多错误。
我做了一个类,它有一个向量,包括:

  • 模板
  • 运算符重载
  • 矩阵运算

链接 : 矢量.h

#pragma once
#include <vector>
#include <iostream>
template<class T>
class Vector
{
public:
Vector();
Vector(int);
Vector(int, int);
~Vector();
std::vector<std::vector<T>> v;
bool Check_Size() ;
template<typename T1> bool Check_Size(std::vector<T1>&) ;
template<typename T1> bool Check_Size_Fast(std::vector<T1>&);
void Print();
void Transponse();
void Inverse();
void Inverse2();
void Inverse3();

template<class T,class Q>
friend std::vector<std::vector<T>> operator* (const Q , Vector<T> );
template<class T,class Q>
friend std::vector<std::vector<T>> operator* (Vector<T> , const Q );
template<class T>
friend std::vector<std::vector<T>> operator*(Vector<T>& , Vector<T>&);
template<typename T>
friend std::vector<std::vector<T>> operator+(Vector<T> &, Vector<T> &);
template<typename T>
friend std::vector<std::vector<T>> operator-(Vector<T> &, Vector<T> &);

Vector<T>& operator = (const std::vector<std::vector<T>>& v)
{
this->v = v;
return *this;
}
std::vector<std::vector<T>>& operator +=( Vector<T>&v) {
return v + (*this);
}
std::vector<std::vector<T>>& operator -=(Vector<T>&v) {
return v - (*this);
}
std::vector<std::vector<T>>& operator *=(Vector<T>&v) {
return v * (*this);
}

private:
void Recursive_Check(std::vector<T>&);
};