我有模板类Matrix,我想在没有stl的情况下为其创建容器,但是我在向容器中添加矩阵时遇到了问题(相同的矩阵!!!)。我创建了一个临时容器来获取所有数据,然后从容器中删除所有数据。我在容器中为+1矩阵创建了新空间,然后尝试将所有内容放到新容器中:
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];
}
}
}
我已经尝试了所有方法,但是每次遇到此行都会失败