2014-03-13 72 views
-1

代碼與VS和Xcode編譯得很好,但當然g ++不喜歡它。我一直盯着這幾個小時,只是在盤旋。 Theres好Karma在這一個! :)try + catch塊上的g ++錯誤異常

這裏是G的版本++我使用:

[...]$ g++ --version 
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-54) 

這裏是代碼:

Item* Library::findItem(unsigned int hash) { 

//retrieve reference to Items::AllItems 
std::map<unsigned int, Item*>& allItems = MyItems.getItems(); 

Item* item = NULL; 

try { 
    item = allItems.at(hash); 
} 
//LINE 74 BELOW: the catch line 
catch (const std::out_of_range& e) { 
    return NULL; 
} 
return item; 
} 

以下是錯誤:

library.cpp: In member function ‘Item* Library::findItem(unsigned int)’: 
library.cpp:74: error: expected `(' before ‘{’ token 
library.cpp:74: error: expected type-specifier before ‘{’ token 
library.cpp:74: error: expected `)' before ‘{’ token 
+0

究竟是什麼在第74行? –

+2

我會冒險猜測:GCC 4.1.2是從2007年開始的,因此它不支持C++ 11功能,並且在C++ 11中引入了std :: map :: at。你可以使用std :: map :: find來替代std :: map :: at,並將try/catch塊徹底拋開。 –

+0

74行是「catch」的行。 –

回答

1

這將產生相同的錯誤,但不包括:

//#include <stdexcept> 

int main(int argc, char* argv[]) { 
    try {} 
    catch(const std::out_of_range&) {} 
} 

g ++ 4.7.2

+0

絕對美麗。程序編譯並運行得很好。我需要做的就是添加包含。天啊! –

0

我會將我的評論變成答案。我想GCC實際上是在抱怨使用std::map::at,這是introduced with C++11,因此不支持GCC 4.1.2,這是released in 2007。我會重寫這樣的代碼:

Item* Library::findItem(unsigned int hash) { 
    std::map<unsigned int, Item*>& allItems = MyItems.getItems(); 
    const std::map<unsigned int, Item*>::iterator it = allItems.find(hash); 
    if (it == allItems.end()) 
     return NULL; 
    return it->second; 
}