'no matching function call' 将类型插入 std::map 时
'no matching function call' when inserting type into std::map
我有以下设置:
一个Instruction
结构:
struct Instruction {
Instruction( const std::string& _opcode) : opcode(_opcode) {}
std::bitset<6> opcode;
};
包含将字符串映射到指令的映射的结构:
class Parser{
Parser();
private:
std::map<std::string, Instruction> instr_map;
};
在 parser
的构造函数中,我尝试使用一些值初始化地图:
Parser::Parser(){
instr_map["add"] = Instruction("101010");
}
上述操作的结果是编译错误:
error: no matching function call to Instruction::Instruction()
所以我相信它是构造函数调用的错误,但是,做类似
的事情
Instruction x("101010");
工作得很好,这表明构造函数按预期工作。
我能得到一些帮助来解决为什么会出现这个错误吗?谢谢,祝你有愉快的一天。
如果指定的键尚不存在,instr_map["add"]
创建一个新元素,然后 returns 对该键值的引用。然后您将一个新对象分配给该引用值。所以键的值必须首先是默认构造的,但你的 Instruction
不是,因此错误。
如果您想跳过该默认创建,请尝试以下方式:
instr_map.emplace("add", "101010");
我有以下设置:
一个Instruction
结构:
struct Instruction {
Instruction( const std::string& _opcode) : opcode(_opcode) {}
std::bitset<6> opcode;
};
包含将字符串映射到指令的映射的结构:
class Parser{
Parser();
private:
std::map<std::string, Instruction> instr_map;
};
在 parser
的构造函数中,我尝试使用一些值初始化地图:
Parser::Parser(){
instr_map["add"] = Instruction("101010");
}
上述操作的结果是编译错误:
error: no matching function call to Instruction::Instruction()
所以我相信它是构造函数调用的错误,但是,做类似
的事情Instruction x("101010");
工作得很好,这表明构造函数按预期工作。
我能得到一些帮助来解决为什么会出现这个错误吗?谢谢,祝你有愉快的一天。
instr_map["add"]
创建一个新元素,然后 returns 对该键值的引用。然后您将一个新对象分配给该引用值。所以键的值必须首先是默认构造的,但你的 Instruction
不是,因此错误。
如果您想跳过该默认创建,请尝试以下方式:
instr_map.emplace("add", "101010");