使用 "new" 命令在 C++ 中的类构造函数中分配 2D 数组

using "new" command to allocate 2d array inside class constructor in c++

本文关键字:构造函数 分配 2D 数组 命令 C++ 使用 new      更新时间:2023-10-16

我正在尝试使用 c++ 编写自己的矩阵类。我想使用 new 运算符为此目的分配堆内存。以下是类代码段,这将引发错误:

class Matrix
{
private:
int *m_ptr;
const int m_size;
public:
Matrix():m_size(2)
{
new int[m_size][m_size];//testing this statement
}   
~Matrix()
{
delete[] m_ptr;
}
};

错误:

main.cc: In constructor ‘Matrix::Matrix()’:
main.cc:11:26: error: array size in new-expression must be constant
new int[m_size][m_size];//testing this statement
^
main.cc:11:26: error: ‘this’ is not a constant expression

m_size必须是常量表达式。不一定是合格的。

您可以尝试将其设为constexpr(但这意味着是静态的(:

static constexpr int m_size = 2;

或使用模板:

template<size_t m_size>
class Matrix {
private:
int *m_ptr;
public:
Matrix(){
new int[m_size][m_size];//testing this statement
}   
~Matrix(){
delete[] m_ptr;
}
};
int main() {
Matrix<2> m;
}

如果找到括号 [],则向右展开新表达式和声明,并且没有括号来更改顺序,如果有括号,则向外展开。

new int[A][B];

这意味着分配A类型为int[B]的元素。A可以是变量,B不能,它是类型定义的一部分。通过单个新表达式分配二维数组的问题通常无法通过语法方式解决。

多维数组本身并未定义为一种类型。我们有对象和对象数组。2D 数组是作为数组的对象数组。由于您无法分配动态类型的对象数组,只能分配静态对象数组,因此无法执行预期操作。相反,您需要一个类包装器,它将通过重新定义operator[]将简单数组视为二维数组。