2017-03-16 66 views
-1

我正在爲學校做一個小項目,並且需要創建一個具有怪物類型的枚舉,然後是一個函數,它接受一個值並將怪物類型顯示爲一個字符串。這裏是我的代碼位:從枚舉顯示爲字符串的C++名稱

enum MonsterType 
{ 
    GHOST, 
    DRAGON, 
    GHOUL, 
    SHRIEKER, 
    GRIFFIN, 
}; 

string getTypeName() 
{ 
    int ID; 
    cout << "Input Monster ID" << endl; 
    cin >> ID; 
    return MonsterType(ID); 
} 

我得到的錯誤有以下幾種:

no suitable constructor exists to convert from "MonsterType" to "std::basic_string<char, std::char_traits<char>, std::allocator<char>>" 

'return': cannot convert from 'MonsterType' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' 

我敢肯定有我缺少一個小東西並沒有意識到,如果你能幫助我,我會非常感激。

謝謝

+0

_I'm肯定有一點小小的轉換我不知道_什麼讓你如此肯定,有'MonsterType'和'std :: string'之間的轉換?它應該如何表現? –

+0

不,我的意思是我可以做的轉換。這可能只是我錯過的一件小事,並沒有意識到。 –

+3

[如何將枚舉類型變量轉換爲字符串?](http://stackoverflow.com/questions/5093460/how-to-convert-an-enum-type-variable-to-a-string) – rsp

回答

0

你可以做的是

enum MonsterType 
{ 
    GHOST, 
    DRAGON, 
    GHOUL, 
    SHRIEKER, 
    GRIFFIN, 
}; 

string GetName(MonsterType monsterType){ 
    string monsterNames[] = {"Ghost", "Dragon", "Ghoul", "Shriker", "Griffin"}; 
    return monsterNames[monsterType]; 
} 
+2

這有很大的機會與enum定義不同步。最好使用包含'enum'標識符和文本的結構。以互聯網或StackOverflow爲例。 –

+0

非常感謝您的回覆,但是這種類型的擊敗使用枚舉類型的目的不是這樣嗎? –

+0

是的,這是真的,但作爲一個小學校項目應該是足夠的 – Luci

0

這兩種錯誤是說同樣的事情。

您的return MonsterType(ID)正在獲取新的MonsterType,並試圖將其返回。

函數的原型string getTypeName()(確實應該string getTypeName(void)如果你想說「沒有參數」),所以你這樣嘗試新MonsterType變量轉換成string。編譯器抱怨說它不知道如何做到這一點。

解決此問題的最佳方法是爲您定義的每種導師類型創建文本(string)表示的列表,並在它們之間建立函數映射。

#include <iostream> 

#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[-1])) 

using namespace std; 

enum MonsterType 
{ 
    GHOST, 
    DRAGON, 
    GHOUL, 
    SHRIEKER, 
    GRIFFIN, 
}; 

string MonsterNames[] = { 
    "Ghost", 
    "Dragon", 
    "Ghoul", 
    "Shrieker", 
    "Griffin", 
}; 

string getTypeName() 
{ 
    int ID; 

    cout << "Input Monster ID" << endl; 

    cin >> ID; 

    if (ID < ARRAY_SIZE(MonsterNames)) { 
     return MonsterNames[ID]; 
    } 
    return "unknown"; 
} 

int main(void) { 
    cout << getTypeName() << endl; 
} 

enum只是一個'事物'的列表,由一個數字標識。您不能以字符串的形式訪問該事物的名稱,而只能將其作爲「關鍵字」。

+0

好吧,我想這是做到這一點的唯一簡單方法。非常感謝你。 –