我在阅读《C++ 程序设计语言》第 4 版时偶然发现了这段代码
template<class T>
class Matrix {
array<int,2> dim; // two dimensions
T∗ elem; // pointer to dim[0]*dim[1] elements of type T
public:
Matrix(int d1, int d2) :dim{d1,d2}, elem{new T[d1∗d2]} {} // error handling omitted
int size() const { return dim[0]∗dim[1]; }
Matrix(const Matrix&); // copy constructor
Matrix& operator=(const Matrix&); // copy assignment
Matrix(Matrix&&); // move constructor
Matrix& operator=(Matrix&&); // move assignment
˜Matrix() { delete[] elem; }
// ...
};
类中有两个数据成员,其中一个是T
类型的指针。 .我无法理解什么 array< int, 2 >
dim
意味着。
最佳答案
成员变量dim
存储二维矩阵的第一维和第二维的大小,Matrix< T >
.这两个尺寸存储为 array< int, 2 >
(我假设 std::array< int, 2 >
:一个类型为 int
的两个值的数组)。
没有这个成员变量dim
, Matrix< T >
不知道其堆分配数组中包含多少元素 elem
(注意 elem
是指向连续元素数组中包含的第一个元素的指针)。所以Matrix< T >
无法安全地迭代这些元素,因为它不知道何时停止。 (实际上,Matrix< T >
可以执行的唯一有用操作是释放分配给堆的数组,就像析构函数中的情况一样。)因此,分配给堆的数组(即 dim[0] * dim[1]
)的大小显式存储为好吧。
关于c++ - array<int,2> dim 在这段代码中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845876/