简体   繁体   English

将函数指针用作映射参数时出错? C ++

[英]Error with a function pointer as a map parameter? C++

I seem to be getting several errors with 我似乎在遇到一些错误

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

Notably, 值得注意的是,

 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

Unfortunately, I can't seem to find what I've done wrong, as it seems to deal with that map declaration which was given to the class by my instructor. 不幸的是,我似乎找不到我做错了什么,因为它似乎处理了由我的讲师提供给班级的那个地图声明。 Below is my .cpp 以下是我的.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;
}

Any suggestions? 有什么建议么? I'm unfamiliar with maps, but I believe this should work, right? 我不熟悉地图,但是我认为这应该可行,对吗?

Coding in pico, compiling with a makefile using g++. 用pico编码,使用g ++编译一个makefile。

It looks like you just are forgetting to add -std=c++11 or -std=c++0x to your compiler flags to enable C++11. 看来您只是忘记在编译器标志中添加-std=c++11-std=c++0x以启用C ++ 11。

-std=c++0x is deprecated, but on older versions of g++, -std=c++11 is not available. -std=c++0x已过时,但在旧版本的g ++上, -std=c++11不可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM