下面是一个简单的 mystring 类,它可以复现上述问题:
#include <iostream>
#include <map>
#include <string>
class mystring {
public:
mystring() = default;
mystring(const char* s) : data(s) {}
// 禁止从 int 直接构造
explicit mystring(int) = delete;
// 允许从 char 赋值
mystring& operator=(char c) {
data = c; // 这样 `mystring m = 1;` 仍然会报错
return *this;
}
friend std::ostream& operator<<(std::ostream& os, const mystring& s) {
return os << s.data;
}
private:
std::string data;
};
void f() {
std::map<std::string, mystring> a;
// 这行会编译失败
mystring m = 2;
// 这行编译成功,原因与 std::string 相同
//a["hello"] = 1;
std::cout << "a[\"hello\"] = " << a["hello"] << std::endl;
}
int main() {
f();
return 0;
}
【 在 DoorWay 的大作中提到: 】
: 在提供的代码中,两处涉及隐式转换的行为导致了不同的编译结果,原因如下:
: 1. std::string m = 2; 编译失败
: 问题分析
: ...................
--
修改:DoorWay FROM 61.185.195.*
FROM 61.185.195.*