如何C ++隐式转换c样式字符串为字符串对象? [英] how C++ Implicitly convert c style string to a string object?
问题描述
string s =abc;
上述语句将首先调用 注意: 使用语法初始化对象 称为复制初始化。 有几种情况是合法的初始化。在所有情况下,RHS必须可转换为 一个字符串文字可以转换为 string(const char * s) code>构造函数,然后根据调用复制构造函数是C ++中字符串初始化的区别吗?
这里是问题:C ++如何知道应该调用 string(const char * s)
将字符串abc转换为临时字符串对象? p>
复制初始化时不会调用复制构造函数。
string s =abc
string
才能正常工作。
string
是通过 string
的构造函数获取 char const *
。这称为用户定义的转化。
string s = "abc";
The above statement will first invoke string ( const char * s )
constructor, then invoke copy constructor according to What are the differences in string initialization in C++? .
Here is the question: how C++ know it should invoke string ( const char * s )
to convert literal string "abc" to a temporary string object?
Note: copy constructor won't be invoked in copy initialization.
Initializing an object by using the syntax
string s = "abc";
is called copy initialization.
There are several scenarios where that is legal initialization. In all cases the RHS must be convertible to a string
for it to work.
One way a string literal can be converted to a string
is through the constructor of string
that takes a char const*
. That is called a user defined conversion.
这篇关于如何C ++隐式转换c样式字符串为字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!