代码:块Mingw编译器错误:可变大小的对象可能未初始化 [英] Code:Blocks Mingw Compiler Error: Variable-Sized Object May Not Be Initialized

查看:335
本文介绍了代码:块Mingw编译器错误:可变大小的对象可能未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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 ++的一部分,但几个编译器支持此功能作为扩展包括gcc

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说可变长度数组不能有一个初始化器,从草案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:


要初始化的实体的类型应为未知
大小的数组对象类型不是可变长度数组类型。

The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.

并且可选择使用:

string items[] = { ... } ;

并且未知大小的数组的大小将由初始化器中的元素数量决定。

and array of unknown size will have its size determined by the number of elements in the initializer.

或者,使用可变大小数组的常用C ++方法是使用 std :: vector

Alternatively the idiomatic C++ way to have array of variable size would be to use std::vector.

这篇关于代码:块Mingw编译器错误:可变大小的对象可能未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆