我正试着用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发布于 2019-09-12 01:19:57
m_size必须是常量表达式。不一定是const合格的。
您可以尝试将其设置为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;
}发布于 2019-09-12 16:06:00
如果找到方括号[],新的表达式和声明将向右展开,并且没有括号来更改顺序,如果有括号,则向外展开。
new int[A][B];这意味着分配int[B]类型的A元素。A可以是变量,但B不能,它是类型定义的一部分。用一个新的表达式来分配二维数组的问题通常是无法用语法手段解决的。
多维数组本身并没有定义为一种类型。我们有对象和对象数组。2D数组是对象的数组,这些对象是数组。由于您不能分配动态类型的对象数组,只能分配静态类型的对象数组,因此无法执行您想要的操作。相反,您需要一个类包装器,它通过重新定义operator[]将简单的数组视为二维数组。
https://stackoverflow.com/questions/57893981
复制相似问题