[英]Using function pointers in std::map
我是C ++的新手,对带有函数指针的std:map
有问题。
我创建了一个map
,该map
具有一个string
作为键,并存储了一个函数指针作为值。 当我尝试使用insert()
函数添加函数指针时,我遇到了麻烦。 但是,当我使用[]
运算符时,它可以工作。 如果可以,请说明这种差异。
这是我编写的示例代码。
OperatorFactory.h
#ifndef OPERATORFACTORY_H
#define OPERATORFACTORY_H
#include <string>
#include <map>
using namespace std;
class OperatorFactory
{
public:
static bool AddOperator(string sOperator, void* (*fSolvingFunction)(void*));
static bool RemoveOperator(string sOperator);
static void RemoveAllOperators();
private:
static map<string , void* (*) (void*)> map_OperatorMap;
};
// Static member re-declaration
map<string, void* (*) (void*)> OperatorFactory::map_OperatorMap;
#endif // OPERATORFACTORY_H
OperatorFactory.cpp
#include "OperatorFactory.h"
void OperatorFactory::RemoveAllOperators()
{
map_OperatorMap.clear();
}
bool OperatorFactory::RemoveOperator(string sOperator)
{
return map_OperatorMap.erase(sOperator) != 0;
}
bool OperatorFactory::AddOperator(string sOperator, void* (*fSolvingFunction)(void*))
{
// This line works well.
map_OperatorMap[sOperator] = fSolvingFunction;
// But this line doesn't.
// map_OperatorMap.insert(sOperator, fSolvingFunction); // Error
return true;
}
错误说:
error: no matching function for call to 'std::map<std::basic_string<char>, void* (*)(void*)>::insert(std::string&, void* (*&)(void*))'
即使使用[]
运算符进行了此工作(编译),我仍想知道为什么在使用insert()
时出现错误。
谢谢。
您使用键和值的std :: pair将元素插入std :: map中:
map.insert(std::make_pair(key,value));
或者,您可以在c ++ 11中放置值:
map.emplace(key,value);
[]运算符返回对传入的键的值的引用:
value_type &
并自动为该键构造一个元素(如果尚不存在)。 使用它们之前,请确保您了解insert()和[]运算符之间的行为差异(例如,后者将替换键的现有值)。
有关更多信息,请参见http://en.cppreference.com/w/cpp/container/map 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.