7

我已经定义了一个数据结构

std::map<std::string, int> a;

我发现我可以将 const char* 作为键传递,如下所示:

a["abc"] = 1;

哪个函数提供从 const char* 到 std::string 的自动类型转换?

4

4 回答 4

16

std::string有一个构造函数,允许从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

struct Foo 
{
  explicit Foo(int) {}
};

Foo f = 33+9; // error
Foo f(33+9); // OK
f = Foo(33+9); // OK
于 2012-12-05T14:54:19.737 回答
4

std::string 有一个构造函数,它以 const char* 作为参数。

string::string(const char*);

除非构造函数被显式声明,否则编译器将在需要调用任何函数时应用一种使用定义的转换。

于 2012-12-05T14:55:20.910 回答
3

请参阅字符串构造函数。构造函数提供映射中键的转换。相当于

a[std::string("abc")] = 1;
于 2012-12-05T14:56:01.663 回答
2

在 C++ 中,如果您创建一个只接受一个参数的类构造函数,那么(除非您用 另有说明explicit),该参数的类型将隐式转换为您的类。

std::string有这样的构造函数char *

是的,这有时会导致一些意外行为。这就是为什么您通常应该explicit使用单参数构造函数的原因,除非您真的想要这些静默转换。

于 2012-12-05T14:59:42.427 回答