为什么我可以在 std::map<std::string, int> 中使用 const char* 作为键? [英] Why I can use const char* as key in std::map<std::string, int>
本文介绍了为什么我可以在 std::map<std::string, int> 中使用 const char* 作为键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经定义了一个数据结构
I have define a data structure
std::map<std::string, int> a;
我发现我可以通过 const char* 作为键,就像这样:
I found I can pass const char* as key, like this:
a["abc"] = 1;
哪个函数提供了从 const char* 到 std::string 的自动类型转换?
Which function provides automatic type conversion from const char* to std::string?
推荐答案
std::string
有一个 构造函数,允许从 const char*
进行隐式转换.
std::string
has a constructor that allows the implicit conversion from const char*
.
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
表示隐式转换,例如
std::string s = "Hello";
允许.
这相当于做类似的事情
struct Foo
{
Foo() {}
Foo(int) {} // implicit converting constructor.
};
Foo f1 = 42;
Foo f2;
f2 = 33 + 9;
如果您想禁止隐式转换构造,请将构造函数标记为explicit
:
If you wanted to disallow the implicit conversion construction, you mark the constructor as explicit
:
struct Foo
{
explicit Foo(int) {}
};
Foo f = 33+9; // error
Foo f(33+9); // OK
f = Foo(33+9); // OK
这篇关于为什么我可以在 std::map<std::string, int> 中使用 const char* 作为键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文