c++ - array<int,2> dim 在这段代码中是什么意思?

标签 c++ arrays c++11 templates copy-constructor

我在阅读《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/

相关文章:

c++ - 提取所有可能的有序子集

php - 如何在html上使用php数组变量输出一个ul列表?

c++ - 椭圆的线宽不是常数

c++ - 使用多个线程的并行 vector 乘法比顺序 vector 乘法花费更长的时间

c++ - 为什么在现阶段,大多数现代 C++ 编译器只支持有限的 C++0x 功能,而 Clang/GCC 支持所有这些功能?

c++ - 获取系统语言UWP C++/WinRT

c++ - 在 Vista 上调用 CoCreateInstance 时是否可以降低权限级别?

python - 从 PyCharm 调试到 Visual Studio C++ 代码

javascript - 将类似字符串的数组替换为带有字符替换的数组

arrays - 使用 make 或默认初始化的不同大小的数组