为什么 C++ 允许将整数分配给字符串?

2024-05-12C/C++开发问题
10

本文介绍了为什么 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.

代码大概是这样的:

std::string my_string("");
unsigned int my_number = 1234;
my_string = my_number;

以下代码也可以很好地编译:

The following code also compiles fine:

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);

这是怎么回事?为什么编译器会用最后一个代码块停止构建,而让前 2 个代码块构建?

What is going on? How come the compiler will stop the build with the last code block, but let the first 2 code blocks build?

推荐答案

因为 string 可以从 char 赋值,而 int 可以隐式转换为 char.

Because string is assignable from char, and int is implicitly convertible to char.

这篇关于为什么 C++ 允许将整数分配给字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6