cout 语句中的字符串文字和字符串之间的区别?
以下打印字符串的方式有什么区别?
std::cout << "hello";
// and
std::cout << std::string("hello");
他们似乎都在做同样的事情。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
以下打印字符串的方式有什么区别?
std::cout << "hello";
// and
std::cout << std::string("hello");
他们似乎都在做同样的事情。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(2)
情况 1
这里我们考虑以下语句:
在上面的语句中,
"hello"
是一个const char[6]
类型的字符串文字,其中由于类型衰减,>衰减为const char*
。然后将此 const char* 传递给operator<<
给出如下:情况 2
这里我们考虑语句:
在上面的语句中,表达式
std::string("hello")
创建一个临时std::string
对象。现在,由于std::string
已重载operator<<
(如下所示),将调用operator<<
的重载版本并执行其主体。Case 1
Here we consider the statement:
In the above statement
"hello"
is a string literal of typeconst char[6]
which decays to aconst char*
due to type decay. Thisconst char*
is then passed to the non-member overload ofoperator<<
given below:Case 2
Here we consider the statement:
In the above statement the expression
std::string("hello")
creates a temporarystd::string
object. Now since thestd::string
has overloadedoperator<<
(given below), that overloaded version ofoperator<<
will be called and its body will be executed.std::cout << "hello";
使用运算符<< /code>
处理以 null 结尾的字符数组的重载。
重载的参数:"hello"
,它是一个const char[6]
,传递时衰减为const char*
作为运算符<<std::cout << std::string("hello"); 使用
operator<<
重载。std::string
是std::basic_string、std::allocator>< 的
typedef
/代码>。std::cout << "hello";
uses theoperator<<
overload dealing with null terminated character arrays."hello"
, which is aconst char[6]
, decay s into aconst char*
when passed as an argument to theoperator<<
overload:std::cout << std::string("hello");
uses theoperator<<
overload for dealing with strings.std::string
is atypedef
forstd::basic_string<char, std::char_traits<char>, std::allocator<char>>
.