【问题标题】:How to insert object into std::map while declaration如何在声明时将对象插入 std::map
【发布时间】:2020-02-06 19:10:00
【问题描述】:

问题:

我试图在编译时将类的实例插入到 std::map 中,但总是出现以下错误。

main.cpp:18:12: error: ‘_info’ was not declared in this scope
     _info(1)
        ^

第 18 行指向下面的代码块

15. std::map<std::string, Info > lookup  {
16.      {
17.        "aclk",
18.        _info(1)
19.      }
20.    };

代码:

#include <random>
#include <iostream>
#include <functional>
#include <map>

class Info{
    int _info;
public:
   Info(int info){
     _info = info;
   }   
}; 


 std::map<std::string, Info > lookup  {
  {
    "aclk",
    _info(1)
  }
};

int main()
{
   //dummy
}

观察:

当我动态创建对象时,我看不到任何此类错误。

const std::map<std::string, Info > lookup  {
  {
    "aclk",
    new Info(1)
  }
};

但是映射为const 并使用new 插入实例没有任何意义。

【问题讨论】:

  • lookup 不是Info 的成员函数,因此它不知道任何名为_info 的东西。如果要创建Info 类型的对象,则应使用该名称:{"aclk", Info(1)}
  • 为什么不直接{ "aclk", Info(1) } 或直接{ "aclk", 1 }

标签: c++ class dictionary constructor initialization


【解决方案1】:

您必须提供Info 类型的对象,而不是其数据成员_info。例如

 std::map<std::string, Info > lookup  {
  {
    "aclk",
    1
  }
};

这是有效的,因为类 Info 有一个转换构造函数。

或者(例如,如果构造函数是显式的)

 std::map<std::string, Info > lookup  {
  {
    "aclk",
    Info(1)
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    相关资源
    最近更新 更多