2

我正在使用C++創建一個簡單的終端幻想遊戲。我似乎遇到了一個錯誤「錯誤:可變大小的對象」項目可能不會被初始化「。這裏是代碼:代碼:Blocks Mingw編譯器錯誤:可變大小的對象可能未初始化

string useItem(int item) 
{ 
    string items[item] = {"HP Potion","Attack Potion","Defense Potion","Revive","Paralize Cure"}; 
} 

我希望能夠使用此功能,以訪問和返回一個項目。我該如何解決這個錯誤。我用mingw編譯器使用Code :: Blocks。

+0

原始數組大小在編譯時必須已知。否則,你應該使用std :: vector Borgleader 2014-12-07 02:46:57

+0

'char const * items [] = ...'? – 2014-12-07 02:47:02

+0

注意你正在使用的編譯器和版本也很有幫助,在這種情況下,答案不會有太大變化,但在其他問題中,它可能會產生很大的變化。 – 2014-12-07 03:32:42

回答

2

這裏有幾個問題,一個可變長度數組是C99功能,不是ISO C++的一部分,但幾個編譯器支持該功能,作爲擴展including gcc

其次C99說,可變長度數組不能有一個初始化,從draft C99 standard6.7.8初始化

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[] = { ... } ; 

和未知陣列大小的大小將由初始化程序中元素的數量決定。

或者,使用可變大小數組的慣用C++方法是使用std::vector

相關問題