C++ 模板 Class 数组指针的动态数组
C++ Template Class Dynamic Array of Pointers to Arrays
我正在用 C++ 制作模板化矩阵 class。为了创建这个 class 我正在创建一个指针数组,这些指针指向动态数组。
到目前为止我有:
template<typename T> class Matrix
{
public:
//constructor
int **m = new int*[_rows];
for (int i = 0; i < _rows; i++)
{
m[i] = new int[_cols];
}
//destructor
for (int i = 0; i < _rows; i++)
{
delete[] m[i]
}
delete[] m;
};
我还想创建一些函数来操作这个结构。
我已经看到很多与此类似的代码,但我没有看到它如何创建一个包含指向其他数组的指针的数组。这个概念让我感到困惑,我只想有人向我澄清我应该如何做我想做的事。
我希望 class 被隔离并且与输入没有任何关系。它可能会在其他代码中调用并使用我的函数来创建矩阵结构。创建一个指针数组对我来说并不是令人困惑的部分,它使这些指针指向其他数组,并且指针数组的大小根据输入条目的数量而增加。
#include <iostream>
using namespace std;
template<typename T> class Matrix
{
public:
Matrix(int row, int col)
{
_rows = row;
_cols = col;
m = new T*[_rows];
for (int i = 0; i < _rows; i++)
{
m[i] = new T[_cols];
for(int j=0; j < _cols; j++)
{
m[i][j] = i*10 + j;
}
}
}
~Matrix()
{
for (int i = 0; i < _rows; i++)
{
delete[] m[i];
}
delete[] m;
}
T **m;
int _rows;
int _cols;
};
void main()
{
Matrix<int> a(3,4);
for(int i=0; i<a._rows; i++)
{
for(int j=0; j<a._cols; j++)
{
cout << "[" << i << "][" << j << "]" << a.m[i][j] << " ";
}
cout << endl;
}
}
结果:
[0][0]0 [0][1]1 [0][2]2 [0][3]3
[1][0]10 [1][1]11 [1][2]12 [1][3]13
[2][0]20 [2][1]21 [2][2]22 [2][3]23
我正在用 C++ 制作模板化矩阵 class。为了创建这个 class 我正在创建一个指针数组,这些指针指向动态数组。
到目前为止我有:
template<typename T> class Matrix
{
public:
//constructor
int **m = new int*[_rows];
for (int i = 0; i < _rows; i++)
{
m[i] = new int[_cols];
}
//destructor
for (int i = 0; i < _rows; i++)
{
delete[] m[i]
}
delete[] m;
};
我还想创建一些函数来操作这个结构。 我已经看到很多与此类似的代码,但我没有看到它如何创建一个包含指向其他数组的指针的数组。这个概念让我感到困惑,我只想有人向我澄清我应该如何做我想做的事。
我希望 class 被隔离并且与输入没有任何关系。它可能会在其他代码中调用并使用我的函数来创建矩阵结构。创建一个指针数组对我来说并不是令人困惑的部分,它使这些指针指向其他数组,并且指针数组的大小根据输入条目的数量而增加。
#include <iostream>
using namespace std;
template<typename T> class Matrix
{
public:
Matrix(int row, int col)
{
_rows = row;
_cols = col;
m = new T*[_rows];
for (int i = 0; i < _rows; i++)
{
m[i] = new T[_cols];
for(int j=0; j < _cols; j++)
{
m[i][j] = i*10 + j;
}
}
}
~Matrix()
{
for (int i = 0; i < _rows; i++)
{
delete[] m[i];
}
delete[] m;
}
T **m;
int _rows;
int _cols;
};
void main()
{
Matrix<int> a(3,4);
for(int i=0; i<a._rows; i++)
{
for(int j=0; j<a._cols; j++)
{
cout << "[" << i << "][" << j << "]" << a.m[i][j] << " ";
}
cout << endl;
}
}
结果:
[0][0]0 [0][1]1 [0][2]2 [0][3]3
[1][0]10 [1][1]11 [1][2]12 [1][3]13
[2][0]20 [2][1]21 [2][2]22 [2][3]23