在c ++类型的构造函数中强制转换

G-7*_*-71 6 c++

我有以下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)

  • `std :: string s2 = s1;`调用复制构造函数,因为它是一个声明. (7认同)