函数指针作为映射参数出错? C ++

时间:2013-10-04 03:18:12

标签: c++ function pointers map

我似乎在使用

时遇到了一些错误
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。

1 个答案:

答案 0 :(得分:1)

看起来您只是忘记将-std=c++11-std=c++0x添加到编译器标志中以启用C ++ 11。

不推荐使用

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