c++ “no matching function for call to” error with structure

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

I have C++ code that maps GUID(unsigned long) to structure.

#include  #include  #include   typedef unsigned long GUID;  enum Function {   ADDER = 1,   SUBTRACTOR = 2,   MULTIPLIER = 3,   SQUAREROOT = 4 };  struct PluginInfo {     GUID guid;     std::string name;     Function function;      PluginInfo(GUID _guid, std::string _name, Function _function) {guid = _guid, name = _name, function = _function;} };  typedef std::map PluginDB;  PluginInfo temp1(1, "Adder", ADDER); PluginInfo temp2(2, "Multiplier", MULTIPLIER);  PluginDB::value_type pluginDbArray[] = {     PluginDB::value_type(1, temp1),     PluginDB::value_type(2, temp2) };  const int numElems = sizeof pluginDbArray / sizeof pluginDbArray[0]; PluginDB pluginDB(pluginDbArray, pluginDbArray + numElems);  int main() {     std::cout 

When I compile it, I got error message.

/usr/include/c++/4.2.1/bits/stl_map.h: In member function ‘_Tp& std::map<_key _tp="" _compare="" _alloc="">::operator[](const _Key&) [with _Key = long unsigned int, _Tp = PluginInfo, _Compare = std::less, _Alloc = std::allocator >]’: mockup_api.cpp:58: instantiated from here /usr/include/c++/4.2.1/bits/stl_map.h:350: error: no matching function for call to ‘PluginInfo::PluginInfo()’ mockup_api.cpp:29: note: candidates are: PluginInfo::PluginInfo(GUID, std::string, Function) mockup_api.cpp:24: note:
PluginInfo::PluginInfo(const PluginInfo&)

What might be wrong?

回答1:

Any objects you place in a STL container initialized with an initial number of objects (i.e., you're not initializing an empty container) must have at least one default constructor ... yours does not. In other words your current constructor needs to be initialized with specific objects. There must be one default constructor that is like:

PluginInfo(); 

Requiring no initializers. Alternatively, they can be default initializers like:

PluginInfo(GUID _guid = GUID(),             std::string _name = std::string(),             Function _function = Function()):             guid(_guid), name(_name), function(_function) {} 


回答2:

The problem is that when you say:

 pluginDB[1] 

you try to create an entry in the map (because [1] does not exist) and to do that as Jason points out, you need a default constructor. However, this is NOT a general requirement of standard library containers, only of std::map, and only of operator[] for std::map (and multimap etc.), which is a good reason why IMHO operator[] for maps et al should be done away with - it is far too confusing for new C++ programmers, and useless for experienced ones.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!