2013-10-04 33 views
1

我似乎得到一些錯誤與函數指針作爲地圖參數出錯? C++

map<string,function<XMLSerializable*()>> mapConstructor; 

值得注意的是,

la5.cpp: In function ‘int main(int, char**)’: 
la5.cpp:21:13: error: ‘function’ was not declared in this scope 
la5.cpp:21:43: error: ‘mapConstructor’ was not declared in this scope 
la5.cpp:21:43: error: template argument 2 is invalid 
la5.cpp:21:43: error: template argument 4 is invalid 
la5.cpp:25:58: warning: lambda expressions only available with -std=c++0x or - std=gnu++0x [enabled by default] 
la5.cpp:33:26: error: expected primary-expression before ‘*’ token 
la5.cpp:33:28: error: expected primary-expression before ‘)’ token 
la5.cpp:33:31: error: ‘pFunc’ was not declared in this scope 
make: *** [la5.o] Error 1 

不幸的是,我似乎無法找到我做錯了,因爲它似乎處理這個地圖聲明是由我的導師給班級的。以下是我的.cpp

#include <iostream> 
#include <map> 
#include <string> 
#include <functional> 

#include "Armor.h" 
#include "Weapon.h" 
#include "Item.h" 
#include "Creature.h" 

using namespace std; 

XMLSerializable * constructItem() 
{ 
     return new Item; 
} 

int main(int argc, char * argv[]) 
{ 

    map<string,function<XMLSerializable*()>> mapConstructor; 

    mapConstructor["Item"] = constructItem; 

    mapConstructor["Creature"] = []() {return new Creature; }; 

    cout << "Input the class name, then we'll try to construct it." << endl; 

    string sLookup = " "; 

    cin >> sLookup; 

    function<XMLSerializable*()> pFunc = mapConstructor[sLookup]; 

    if(pFunc() == NULL) 
    { 
      cout << "Sorry, the object couldn't be constructed." << endl; 
    } 
    else 
    { 
      cout << pFunc() << " a non NULL value was returned!" << endl; 
    } 
    return 0; 
} 

有什麼建議嗎?我對地圖不熟悉,但我相信這應該起作用,對吧?

在pico中編碼,使用g ++編譯makefile。

+0

'std :: function'不是一個函數指針,它是各種可調用函數的包裝類,包括函數指針。 – goji

回答

1

看起來你只是忘記將-std=c++11-std=c++0x添加到你的編譯器標誌來啓用C++ 11。

-std=c++0x已棄用,但在舊版本的g ++中,-std=c++11不可用。

+1

這就是我的想法,但提示只說要將-std = C++ 0x放入某個特定位置,所以我沒有對此提出疑問。嘗試使用C++ 0x標準編譯得很好,謝謝! – Nick

+0

@Nick:請記住接受這個答案,如果它幫助你。 –