gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:28:46 26 4
gpt4 key购买 nike

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

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

foobar 需要一个 std::string 作为参数

我从未见过以这种方式完成的转换...在“文本”上调用了什么函数。或者这是一些棘手的类型转换方式?

最佳答案

std::string 有一个构造函数,它接受一个 char-array*(假设以 null 终止),我相信你以前见过:

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

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

此外,还有一个免费的 operator+ 用于 stringconst char * 将数据追加到字符数组中(同样假设为 null-终止)到字符串。

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

对于 std::string 支持的操作列表,请咨询任何体面的 manual .

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

关于c++ - 将字符转换为字符串的代码行 --> foobar(string ("text")+anotherString),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com