cannot appear in a constant expression

孤街浪徒 提交于 2019-12-11 14:55:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!