不能出现在常量表达式中 [英] cannot appear in a constant expression

查看:297
本文介绍了不能出现在常量表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下c ++程序中:

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;
       }
    }
 }
 ...



>我得到以下错误:'n'不能出现在常量表达式。
因为im相对较新的cpp我真的不知道为什么这个错误发生(特别是因为我几乎完全相同的事情与一个类称为矢量,有没有问题)和如何解决它。

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.

推荐答案

在此表达式中

x=new double[n][n];

除了最左边的所有维度都是常数表达式。

all dimensions except the leftmost shall be constant expressions.

正确的方法是

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;
   }
}

或者如果你的编译器支持C ++ 2011,

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] {};

这篇关于不能出现在常量表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆