本文介绍了为什么C ++允许将整数分配给字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个程序中遇到了一个有趣的情况,我不经意地将一个无符号整数赋值给了一个std :: string。 VisualStudio C ++编译器没有给出任何警告或错误,但我偶然注意到,当我运行该项目,它给我的字符串的垃圾字符的错误。
I encountered an interesting situation today in a program where I inadvertantly assigned an unsigned integer to a std::string. The VisualStudio C++ compiler did not give any warnings or errors about it, but I happened to notice the bug when I ran the project and it gave me junk characters for my string.
这是这样的代码看起来像:
This is kind of what the code looked like:
std::string my_string("");
unsigned int my_number = 1234;
my_string = my_number;
以下代码也编译良好:
std::string my_string("");
unsigned int my_number = 1234;
my_string.operator=(my_number);
以下结果出现错误:
unsigned int my_number = 1234;
std::string my_string(my_number);
发生了什么事?
推荐答案
因为字符串是字符串,所以编译器会停止生成最后的代码块。可从 char
分配, int
可隐式转换为 char
。
Because string is assignable from char
, and int
is implicitly convertible to char
.
这篇关于为什么C ++允许将整数分配给字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!