问题描述
我使用C ++创建了一个简单的终端幻想游戏。我似乎遇到一个错误错误:可变大小的对象'项目'可能不会初始化。这是代码:
I am creating a simple terminal fantasy game using C++. I have seemed to run into an error "error: variable-sized object 'items' may not be initialized". Here is the code:
string useItem(int item)
{
string items[item] = {"HP Potion","Attack Potion","Defense Potion","Revive","Paralize Cure"};
}
我希望能够使用此函数访问和返回项目。如何解决这个错误。我使用Code :: Blocks与mingw编译器。
I want to be able to use this function in order to access and return an item. How can I fix this error. I am using Code::Blocks with mingw compiler.
推荐答案
这里有几个问题,一个变长数组是一个C99功能,而不是ISO C ++的一部分,但几个编译器支持此功能作为扩展。
There are a couple of issues here, one variable length arrays is a C99 feature and is not part of the ISO C++ but several compilers support this feature as an extension including gcc.
其次,C99说可变长度数组不能有一个初始化器,从部分 6.7.8
初始化:
Secondly C99 says that variable length arrays can not have an initializer, from the draft C99 standard section 6.7.8
Initialization:
并且可选择使用:
string items[] = { ... } ;
并且未知大小的数组的大小将由初始化器中的元素数量决定。
and array of unknown size will have its size determined by the number of elements in the initializer.
或者,使用可变大小数组的常用C ++方法是使用。
Alternatively the idiomatic C++ way to have array of variable size would be to use std::vector.
这篇关于代码:块Mingw编译器错误:可变大小的对象可能未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!