2012-11-24 74 views
1

我有以下代碼:枚舉引用參數傳遞的不是int引用參數

typedef enum {Z,O,T} num; 
bool toInt (str s,int& n);//<-if convert is possible converts s to integer ,puts the result in n and returns true,else returns false 

我想使用toInt功能和轉移作爲第二個參數,類型NUM的參數 NUM N; toInt(「2」,n); 這會導致編譯錯誤。

cannot convert parameter 2 from 'num' to 'int &' 

我試圖用鑄造:toInt("2",(num)n);但它仍是個問題 我該如何解決這個問題?

+0

什麼是編譯器錯誤?如果你不告訴我們,我們不能幫助你。 – Pubby

+0

@Pubby:更新 – Yakov

+0

它仍然相當模糊,但可能是因爲您需要演員。 – Pubby

回答

1

num類型的值不是int,因此必須在將其傳遞給該函數之前將其轉換爲臨時的int。暫時不能綁定到非const引用。


如果你想通過int轉換,則必須分兩步轉換:

int temp; 
toInt("2", temp); 
num n = static_cast<num>(temp); 
+0

請參閱更新的問題verison(附演員表) – Yakov

1

我會建議你添加一個新的枚舉類型signaing無效枚舉如:

enum num {Z,O,T,Invalid=4711} ;//no need to use typedef in C++ 

和更改簽名爲num的不是int:

bool toInt (str s, num& n) 
{ 
if (s=="Z") n=Z; 
else if (s=="O") n=O; 
else if (s=="T") n=T; 
else { n=Invalid; return false; } 
return true; 
} 

關於