我有以下c ++代码:
#include <iostream>
#include <string>
int main( int argc, char* argv[] )
{
const std::string s1 = "ddd";
std::string s2( std::string( s1 ) );
std::cout << s2 << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
结果是:1为什么?当我使用-Wall标志时,编译器写警告:'std :: string s2(std :: string)'的地址总是计算为'true'
但是这段代码:
#include <iostream>
#include <string>
int main( int argc, char* argv[] )
{
const std::string s1 = "ddd";
std::string s2( ( std::string )( s1 ) );
std::cout << s2 << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
结果:ddd
这是正常的结果
Xeo*_*Xeo 13
std::string s2( std::string( s1 ) );
Run Code Online (Sandbox Code Playgroud)
被解析为"以std::string参数命名s1并返回"的函数的声明std::string.然后尝试打印该函数,该函数首先将其转换为函数指针(正常衰减/转换规则).由于operator<<的std::ostream一般未过载函数指针,它将尝试转换到bool,其成功,并且由于函数指针是非空,它转换为布尔值true,其被打印为1.
将其更改为
std::string s2( (std::string( s1 )) );
Run Code Online (Sandbox Code Playgroud)
或者甚至更好,只是
std::string s2( s1 );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
140 次 |
| 最近记录: |