gpt4 book ai didi

C++::将ASCII值转换为字符串

转载 作者:太空狗 更新时间:2023-10-29 20:13:55 25 4
gpt4 key购买 nike

我正在尝试将表示字符 ASCII 值的 int 转换为单字符字符串。

我尝试了以下方法,但它不起作用:
string s1=(char) 97;

但是,只有当我像这样分解分配时,转换才有效:
字符串 s1;
s1=(char) 97;

我对此感到困惑,谁能解释其中的区别?


提前致谢!

最佳答案

I tried the following, and it does not work: string s1=(char) 97;

那是因为 std::string constructor没有任何需要单个 char 的重载。而且,复制被省略,因此直接调用构造函数,永远不会调用 operator =()(在 copy elision 上记录自己)。

the conversion works only if I break the assignment apart like this: string s1; s1=(char) 97;

现在拷贝不再被省略,你真的在​​调用std::string::operator =() 确实有一个重载接受单个char

关于C++::将ASCII值转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18938740/

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