gpt4 book ai didi

c++ - 如何在声明时将对象插入到 std::map 中

转载 作者:行者123 更新时间:2023-12-02 02:54:55 25 4
gpt4 key购买 nike

问题:

我试图在编译时将类的实例插入到 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)
}
};

但是 map 是 const 并且实例是用 new 插入的没有任何意义。

最佳答案

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

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

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

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

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

关于c++ - 如何在声明时将对象插入到 std::map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58304273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com