使用 "new" 命令在 C++ 中的类构造函数中分配 2D 数组
using "new" command to allocate 2d array inside class constructor in c++
我正在尝试使用 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[]
将简单数组视为二维数组。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 具有自定义构造函数 (C++) 的类型的动态数组分配
- C 字符串在显式构造函数中分配值C++?
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 在构造函数中分配内存失败是如何冒泡的
- 当我尝试通过构造函数分配 char 数组时出现错误
- 如何使用函数(而不是构造函数)将派生类对象分配给基类指针
- 当设置对象等于另一个函数的返回值时,为什么要调用移动构造函数/分配
- 如何安全地释放构造函数分配的资源
- 是否可以在基类中删除复制和移动构造函数/分配运算符
- 如何在隐式复制构造函数/分配运算符中压制成员
- 使用超载构造函数分配
- 使用构造函数分配内存
- 如何使用复杂构造函数分配对象
- 将类构造函数分配给具有参数的新构造函数C++
- 在构造函数分配后更改vtable内存
- 在尝试使用 new 和 copy 构造函数分配内存时,在 '(' 令牌之前获取"预期的非限定 id"
- 为存储库构造函数分配内存
- 由c++中的双默认构造函数分配的值
- 将派生类构造函数分配给基类指针