将字符转换为字符串的代码行 --> foobar( "text" )+otherString)

line of code converting char to string --> foobar(string("text")+anotherString)

本文关键字:gt foobar text +otherString 转换 字符 字符串 代码      更新时间:2023-10-16

我有一行代码似乎可以将char数组转换为字符串

foobar(string("text")+anotherString);

foobar需要一个std::字符串作为参数

我从来没有见过这样的转换。。。对"text"调用了什么函数。或者这是一种棘手的选角方式?

std::string有一个构造函数,它接受一个char数组*(假定为null终止),我相信您以前见过:

std::string s1 = "hello world";
std::string s2("also hello world");  // "same thing", essentially

所以std::string("test")只是创建一个值为"test"的临时字符串对象。

此外,对于stringconst char *,还有一个空闲的operator+,它将char数组中的数据(再次假定为null终止)附加到字符串中。

等效地,您可以编写std::string("test").append(anotherString),以获得相同的效果(即,包含两个字符串的临时字符串,连接在一起)。

有关std::string支持的操作列表,请参阅任何合适的手册。

*),或者更确切地说,"指向字符数组第一个元素的指针"

string("text")通过调用其构造函数并将其传递给"text"来创建一个临时对象字符串。+anotherString部分调用临时创建的"operator+"成员函数,该函数也返回一个字符串对象。最后,调用foobar并传递后一个字符串对象。

它与完全相同

string temp("text");
temp += anotherString;
foobar(temp);

如果这有助于