std :: string如何构造一个名称作为构造函数参数的对象?

jet*_*ett 4 c++

#include <string>          
#include <iostream>        

std::string(foo);          

int main()                 
{                          
    std::cout << foo.size() << "\n";                                                
    return 0;              
}                          
Run Code Online (Sandbox Code Playgroud)

结果0,而不是foo未定义的预期编译错误.

怎么能这样做?这个叫什么?

P.W*_*P.W 10

std::string(foo);  //#1        
Run Code Online (Sandbox Code Playgroud)

是相同的

std::string (foo); //#2         
Run Code Online (Sandbox Code Playgroud)

是相同的

std::string foo; //#3          
Run Code Online (Sandbox Code Playgroud)

括号中的内容#2是多余的.它们是必需的,#1因为没有空格分隔std::stringfoo.