将std :: string作为函数参数传递时的C ++类型转换

时间:2021-08-07 18:47:43

Is passing a string by "" equivalent to passing a string by calling std::str("") in C++?

传递一个字符串“”相当于通过在C ++中调用std :: str(“”)传递一个字符串?

e.g. given a function which accepts std::str as an argument:

例如给定一个接受std :: str作为参数的函数:

void funcA(std::string arg) {
    arg = "abc";
}

Should I call it by funcA(std::string("abc")); or funcA("abc"); ? i.e. is the second version a typecast from an array of char?

我应该通过funcA调用它(std :: string(“abc”));或funcA(“abc”); ?即第二个版本是来自char数组的类型转换吗?

1 个解决方案

#1


4  

They are equivalent. Because the constructor std::string::string( char const * ) is not declared as explicit, it is called implicitly to provide a conversion from char * to string. The implicit call does the same thing as the explicit call (written out as std::string("abc")).

它们是等价的。因为构造函数std :: string :: string(char const *)未声明为显式,所以会隐式调用它以提供从char *到string的转换。隐式调用与显式调用(写为std :: string(“abc”))完全相同。

#1


4  

They are equivalent. Because the constructor std::string::string( char const * ) is not declared as explicit, it is called implicitly to provide a conversion from char * to string. The implicit call does the same thing as the explicit call (written out as std::string("abc")).

它们是等价的。因为构造函数std :: string :: string(char const *)未声明为显式,所以会隐式调用它以提供从char *到string的转换。隐式调用与显式调用(写为std :: string(“abc”))完全相同。