问题
In the following c++ programm:
class matrix {
public:
int n;
double **x;
matrix(int n) : n(n) {
x=new double[n][n];
for (int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
x[i][j]=0;
}
}
}
...
I get the following error: "'n' cannot appear in a constant-expression". Since im relatively new to cpp i dont really know why this error occurs (especially because i did almost the exact same thing with a class called vector and there it was no problem at all) and how to fix it. I would really appreciate any help.
回答1:
In this expression
x=new double[n][n];
all dimensions except the leftmost shall be constant expressions.
The correct approach is
x = new double *[n];
for ( int i = 0; i < n; i++ ) x[i] = new double[n];
for (int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
x[i][j]=0;
}
}
Or if your compiler supports C++ 2011 then it can be done simpler without explicit initialization in the loops
x = new double *[n];
for ( int i = 0; i < n; i++ ) x[i] = new double[n] {};
来源:https://stackoverflow.com/questions/20313343/cannot-appear-in-a-constant-expression