“变量名”不能出现在常量表达式 c++ 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1501768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'variable name' cannot appear in a constant expression c++
提问by Captaindh00m
Anyone have any clue what this error might actually mean? I'm tripping on a bit of code that can't seem to get around it. I've tried it with just h*2 instead of hprime, and just w*2 instead of wprime. Every time I get the same compiler (g++ compiler) error of :
任何人都知道这个错误实际上意味着什么?我被一些似乎无法解决的代码绊倒了。我试过只用 h*2 代替 hprime,用 w*2 代替 wprime。每次我得到相同的编译器(g++ 编译器)错误时:
grid.cpp: In constructor ‘Grid::Grid(int, int)':
grid.cpp:在构造函数'Grid::Grid(int, int)'中:
grid.cpp:34: error: ‘hprime' cannot appear in a constant-expression
grid.cpp:34: 错误:'hprime' 不能出现在常量表达式中
(the compiler doesn't always say hprime, it will say whatever variable is there, be it h or hprime or width). Any help would be greatly appreciated!
(编译器并不总是说 hprime,它会说那里有任何变量,无论是 h 或 hprime 还是宽度)。任何帮助将不胜感激!
class Grid
{
public:
Grid(int x, int y);
~Grid();
void addObstacle(int w, int h);
void toString();
int** grid;
int height;
int width;
};
Grid::Grid(int w, int h)
{
width = w;
height = h;
const int hprime = h*2;
const int wprime = w*2;
grid = new int[wprime][hprime];
for(int x=0;x<wprime;x++) {
for (int y=0; y<hprime;y++) {
grid[x][y] = 0;<br>
}
}
}
回答by Mark Rushakoff
You can't use new
to allocate a two-dimensional array, but you canchange the offending line like this:
您不能用于new
分配二维数组,但您可以像这样更改违规行:
grid = new int*[wprime];
for (int i = 0 ; i < wprime ; i++)
grid[i] = new int[hprime];
If it doesn't haveto be multidimensional, you cando:
如果它不具有是多层面的,你可以这样做:
grid = new int[wprime*hprime];
and just index it like
然后像索引一样
grid[A*wprime + B]
where you would normally index it like
你通常会在哪里索引它
grid[A][B]