如果提供+'0',如何将整数附加到字符串
How can integer be appended to string if + '0' is provided
我在一个编程问题的解决方案中遇到了一个奇怪的代码,我找不到任何好的想法。这里,
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
int count=8;
string temp="Hello ";
temp+=count+'0';
cout<<temp;
return 0;
}
Output is: Hello 8
整数变量计数被附加到字符串,即使没有类型转换整数变量。我猜它之所以起作用是因为“0”,但这个过程或方法是什么。
integer variable count was appended to the string even without type
casting the integer variable.
不,没有附加整型变量。唯一适合 +=
运算符的重载是采用单个 char
参数并最终向字符串添加单个字符的重载。整数值类型被转换为 char
类型,剩下的就是历史了。
因此,字符 '0'
加 8 不出所料,字符 '8'
。当然,如果您的整数变量为负数或大于 9,事情就会朝着令人兴奋的方向发展。您应该尝试一下,结果应该很有启发性。
编译器将进行隐式转换以解析
temp+=count+'0';
可以这样解释,更好理解
temp.operator+=(static_cast<char>(count + static_cast<int>('0')));
因此 0
的 ascii 值将添加到 count
中,十进制的 56
将被转换回 ascii 8
。
为 char
重载的 operator +=
将以 8
作为参数触发。
你甚至可以像下面的代码那样转换你的 3 行,你仍然会得到相同的结果。
int count=56;
string temp="Hello ";
temp+= count;
我在一个编程问题的解决方案中遇到了一个奇怪的代码,我找不到任何好的想法。这里,
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
int count=8;
string temp="Hello ";
temp+=count+'0';
cout<<temp;
return 0;
}
Output is: Hello 8
整数变量计数被附加到字符串,即使没有类型转换整数变量。我猜它之所以起作用是因为“0”,但这个过程或方法是什么。
integer variable count was appended to the string even without type casting the integer variable.
不,没有附加整型变量。唯一适合 +=
运算符的重载是采用单个 char
参数并最终向字符串添加单个字符的重载。整数值类型被转换为 char
类型,剩下的就是历史了。
因此,字符 '0'
加 8 不出所料,字符 '8'
。当然,如果您的整数变量为负数或大于 9,事情就会朝着令人兴奋的方向发展。您应该尝试一下,结果应该很有启发性。
编译器将进行隐式转换以解析
temp+=count+'0';
可以这样解释,更好理解
temp.operator+=(static_cast<char>(count + static_cast<int>('0')));
因此 0
的 ascii 值将添加到 count
中,十进制的 56
将被转换回 ascii 8
。
为 char
重载的 operator +=
将以 8
作为参数触发。
你甚至可以像下面的代码那样转换你的 3 行,你仍然会得到相同的结果。
int count=56;
string temp="Hello ";
temp+= count;