可变大小的对象可能不会被初始化 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23751075/
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-sized object may not be initialized c++
提问by user3102621
I understand that this question was asked before but I don't get why it doesn't work in my case
我知道之前有人问过这个问题,但我不明白为什么它在我的情况下不起作用
void calc(vector<char> zodis1, vector<char> zodis2, vector<char> zodisAts,int zo1,int zo2,int zoA)
{
int i,u=0;
int zod1[zo1]=0;
int zod2[zo2]=0;
int zodA[zoA]=0;
}
All 3 of zod1, zod2, zoA gives me error: variable-sized object may not be initialized c++
But compiler should know the meaning of zo
before initialization cause cout<<zo1;
works and print out the meaning
zod1, zod2, zoA 的所有 3 都给我错误:variable-sized object may not be initialized c++
但是编译器应该知道zo
在初始化原因cout<<zo1;
工作之前的含义并打印出含义
So whats the problem?
所以有什么问题?
回答by Rakib
You can declare an array
only with constantsize, which can be deduced at compile time. zo1
,zo2
and zoA
are variables, and the values can be known only at runtime.
您可以声明一个array
具有常量大小的only ,这可以在编译时推断出来。zo1
,zo2
和zoA
是变量,并且这些值只能在运行时知道。
To elaborate, when you allocate memory on the stack, the size must be known at compile time. Since the arrays are local to the method, they will be placed on the stack. You can either use constant value, or allocate memory in the heapusing new
, and deallocate when done using delete
, like
详细地说,当您在堆栈上分配内存时,必须在编译时知道大小。由于数组是方法的本地数组,因此它们将被放置在堆栈中。您可以使用恒定值,或者在分配内存堆使用new
,并且使用完成后解除分配delete
,如
int* zod1 = new int[zo1];
//.... other code
delete[] zod1;
But you can use vector
instead of array
here also, and vector
will take care of allocation on the heap.
但是你也可以使用这里vector
代替array
,并且vector
会处理堆上的分配。
As a side note, you should not pass vector
by value, as the whole vector will be copied and passed as argument, and no change will be visible at the caller side. Use vector<char>& zodis1
instead.
作为旁注,您不应该vector
按值传递,因为整个向量将被复制并作为参数传递,并且在调用方端看不到任何更改。使用 vector<char>& zodis1
来代替。