C++ 为什么const char*转换为std::string有效?
这个演员阵容让我困惑:C++ 为什么const char*转换为std::string有效?,c++,C++,这个演员阵容让我困惑: #include <string> #include <iostream> #include <memory> using namespace std; int main() { string str1 = (string)"I cast this thing" + " -- then add this"; cout << str1 << endl; } 它们看起来是相同的,所以我觉得我
#include <string>
#include <iostream>
#include <memory>
using namespace std;
int main() {
string str1 = (string)"I cast this thing" + " -- then add this";
cout << str1 << endl;
}
它们看起来是相同的,所以我觉得我忘记了一些C++语义,它们实际上允许这种类型的转换/构造互换。
std::string str2 = std::string("I construct this thing") + " -- then add this";
是的,如果你有一个构造函数,它接受一个像这样的参数,它将被用来将参数类型转换成对象类型。这就是为什么我们可以将
const char*
传递给使用字符串的函数
具有以下形式的
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
它充当转换运算符。如果将字符串文字强制转换为
std::string
,它将调用此构造函数并创建临时std::stringC样式强制转换将执行常量强制转换和静态强制转换或重新解释强制转换(以可能的为准)
静态转换将使用用户定义的转换(如果已定义)
std::string
有一个构造函数string(const char*)
语法std::string(“something”)
、static\u cast(“something”)
和(std::string)“something”
是等价的。他们都将使用std::string::string(const char*)
构造函数构造一个临时的std::string
。语法之间的唯一区别是在投射指针时。(T)x
=T(x)
。除了名称(C样式转换与函数样式转换)之外,这两种转换完全相同。另请参见:完全有意义…出于某种原因,我总是忘记关于静态转换的“有效用户定义转换”。
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );