首页 > 解决方案 > 在没有 stl 的情况下将模板类添加到容器

问题描述

我有模板类 Matrix,我想在没有 stl 的情况下为其创建容器,但是在将矩阵添加到容器时遇到问题(相同的矩阵!!!)。我创建了获取所有数据的临时容器,然后从容器中删除了我的所有数据。我在容器中为 +1 Matrix 创建了新空间,然后尝试将所有内容放入我的新容器中:

template<int row, int col, typename T=int>
class MatrixContainer {
public:
MatrixContainer<row, col, T>() {
    size = 0;
    container = new Matrix<row,col,T>[size];
}
void addMatrix(const Matrix<row, col, T> &mat) {
    this->size=this->size+1;
    Matrix<row,col,T> *temp = new Matrix<row,col,T>[this->size-1];
    for (int i = 0; i < size-1; ++i) {
        temp[i] = this->container[i];
    }
    delete[] this->container;
    this->container = new Matrix<row,col,T>[size];
    for (int i = 0; i < size-1; ++i) {
        this->container[i] = temp[i];
    }
    container[size]=mat;
    delete[]temp;
}
private:
Matrix<row, col, T> *container;
int size;
};

一切都编译,但当它看到

container[size]=mat;

它调用复制构造函数然后失败。这是模板类 Matrix 中的复制构造函数:

Matrix(const Matrix &other) {
    this->elements = new T *[other.rows];
    for (int i = 0; i < other.rows; i++) {
        this->elements[i] = new T[other.cols];
    }
    this->rows = other.rows;
    this->cols = other.cols;
    for (int i = 0; i < this->rows; ++i) {
        for (int j = 0; j < this->cols; ++j) {
            this->elements[i][j] = other.elements[i][j];
        }
    }
}

我已经尝试了所有方法,但是每次收到这条线时都会失败

标签: c++ooptemplatescontainers

解决方案


推荐阅读