前pression必须有一个恒定值误差C ++ [英] expression must have a constant value error in c++
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/972705/is-there-a-way-to-initialize-an-array-with-non-constant-variables-c\">Is有没有办法来初始化非恒变量数组? (C ++)
块引用>我有以下的code:
矢量&lt;矢量&lt;&VEC2 GT;&GT; vinciP;
INT myLines = -1;
myLines = drawPolyLineFile(vinci.dat,vinciP);
如果(myLines -1个)
{
COUT&LT;&LT; \\ n \\ nSUCCESS
VEC2 vPoints [myLines]
的for(int i = 0; I&LT;为NumPoints ++ I)
{
vPoints [I] = vinciP [0] [I];
}
}我收到就行了一个错误'VEC2 vPoints [myLines];上面写着前pressions必须有一个恒定值。我不明白为什么我得到这个错误,任何帮助?
是因为myLines可能是负面的? IDK的。
解决方案VEC2 vPoints [myLines]
由于
myLines
不是的常量的前pression((这意味着,它不是在编译时知道),所以上述code宣称这是不是在C ++允许一个可变长度的数组。只有C99有这个功能。你的编译器可能有这个作为一个扩展(而不是标准的C ++)。这样的黎民问题的解决方法是:用
的std ::矢量&lt; T&GT;
为:的std ::矢量&lt;&VEC2 GT; vPoints(myLines);
它应该现在的工作。
Possible Duplicate:
Is there a way to initialize an array with non-constant variables? (C++)I have the following code:
vector<vector<vec2>> vinciP; int myLines = -1; myLines = drawPolyLineFile("vinci.dat", vinciP); if (myLines > -1) { cout << "\n\nSUCCESS"; vec2 vPoints[myLines]; for (int i = 0; i < NumPoints; ++i) { vPoints[i] = vinciP[0][i]; } }
I'm getting an error on the line 'vec2 vPoints[myLines];' that says expressions must have a constant value. I don't understand why I'm getting this error, any help?
Is it because myLines could be negative? idk.
解决方案vec2 vPoints[myLines];
Since
myLines
is not a const expression ((which means, it is not known at compile-time), so the above code declares a variable length array which is not allowed in C++. Only C99 has this feature. Your compiler might have this as an extension (but that is not Standard C++).The solution to such commom problem is : use
std::vector<T>
as:std::vector<vec2> vPoints(myLines);
It should work now.
这篇关于前pression必须有一个恒定值误差C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!