[英]Why I can use const char* as key in std::map<std::string, int>
I have define a data structure 我已经定义了一个数据结构
std::map<std::string, int> a;
I found I can pass const char* as key, like this: 我发现我可以传递const char *作为键,如下所示:
a["abc"] = 1;
Which function provides automatic type conversion from const char* to std::string? 哪个函数提供从const char *到std :: string的自动类型转换?
std::string
has a constructor that allows the implicit conversion from const char*
. std::string
有一个构造函数,允许从const char*
进行隐式转换 。
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
means that an implicit conversion such as 意味着隐式转换,如
std::string s = "Hello";
is allowed. 被允许。
It is the equivalent of doing something like 这相当于做了类似的事情
struct Foo
{
Foo() {}
Foo(int) {} // implicit converting constructor.
};
Foo f1 = 42;
Foo f2;
f2 = 33 + 9;
If you wanted to disallow the implicit conversion construction, you mark the constructor as explicit
: 如果要禁止隐式转换构造,请将构造函数标记为
explicit
:
struct Foo
{
explicit Foo(int) {}
};
Foo f = 33+9; // error
Foo f(33+9); // OK
f = Foo(33+9); // OK
There is a constructor for std::string which takes const char* as a parameter. std :: string有一个构造函数,它将const char *作为参数。
string::string(const char*);
Unless the constructor is declared explicit then the compiler will apply one use defined conversion if needed to call any function. 除非构造函数声明为显式,否则编译器将根据需要应用一个使用定义的转换来调用任何函数。
See string constructor . 参见字符串构造函数 。 The constructor provides the conversion for the key in your map.
构造函数为地图中的键提供转换。 It's equivalent to
它相当于
a[std::string("abc")] = 1;
In C++ if you make a class constructor that only takes one parameter, then (unless you tell it otherwise with explicit
), that parameter's type will be implicitly convertable to your class. 在C ++中,如果你犯了一个类的构造函数,只需要一个参数,然后(除非你告诉它,否则有
explicit
),该参数的类型将是隐式可转换到您的类。
std::string
has such a constructor for char *
std::string
有一个char *
的构造函数
Yes, this can cause some unexpected behavior on occasion. 是的,这有时可能会导致一些意想不到的行为。 This is why you generally should put
explicit
on single-parameter constructors, unless you really want these silent conversions. 这就是为什么你通常应该在单参数构造函数上
explicit
,除非你真的想要这些静默转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.