C ++表达式必须具有恒定值 [英] c++ expression must have a constant value
本文介绍了C ++表达式必须具有恒定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这种方法:
void createSomething(Items &items)
{
int arr[items.count]; // number of items
}
但是它抛出一个错误:
expression must have a constant value
我发现了以下解决方案:
I found just this solution:
int** arr= new int*[items.count];
所以我问有一种更好的方法来处理这个问题吗?
so I'm asking is there a better way how do handle this?
推荐答案
您可以使用 std :: vector
void createSomething(Items &items)
{
std::vector<int> arr(items.count); // number of items
}
The reason your first method won't work is that the size of an array must be know at compile time (without using compiler extensions), so you have to use dynamically sized arrays. You can use new
to allocate the array yourself
void createSomething(Items &items)
{
int* arr = new int[items.count]; // number of items
// also remember to clean up your memory
delete[] arr;
}
但是使用 std :: vector
更加安全,恕我直言.
But it is safer and IMHO more helpful to use a std::vector
.
这篇关于C ++表达式必须具有恒定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文