【发布时间】:2021-06-23 03:50:45
【问题描述】:
我有一些类似下面的结构来获取静态常量映射:
struct SupportedPorts{
static std::map<std::string, std::string> init()
{
std::map<std::string, std::string> port;
port["COM1"] = "ttySO1";
port["COM2"] = "ttySO2";
port["USB"] = "ttyUSB0";
return port;
}
static const std::map<std::string, std::string> supported_ports;
};
但是当我尝试按键获取一些值时我遇到了问题。在Exmaple类的cpp文件中:
#include "Example.h"
const std::map<std::string, std::string> SupportedPorts::supported_ports = SupportedPorts::init();
Example::Example(){
std::cout << SupportedPorts::supported_ports['COM1'];
}
我收到如下错误:
note: initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
basic_string(const _CharT* __s, const _Alloc& __a = _Alloc());
error: conversion to non-const reference type ‘std::map<std::basic_string<char>, std::basic_string<char> >::key_type&& {aka class std::basic_string<char>&&}’ from rvalue of type ‘std::basic_string<char>’ [-fpermissive]
std::cout << SupportedPorts::supported_ports['COM1'];
^
(null):0: confused by earlier errors, bailing out
【问题讨论】:
-
我看到你刚刚了解到
[]编辑地图
标签: c++ dictionary c++11 stl constants