C++ Builder 允许将字符串与 Int 进行比较 - 为什么?

标签 c++ string c++builder

我最近开始研究使用 C++Builder (Borland) 构建的旧解决方案。

我遇到了允许一些意外操作的代码。

1) 将 int 赋值给 String 而不进行转换:

String x = 12; //this works... I would expect a type mismatch..

2) String 与 int 的比较没有问题:

String s = "12";
int x = 12;
bool b = s == x; // Again... I expect an error..

C++Builder 会做一些自动转换吗? 是否有针对 C++Builder 的“天哪,我不敢相信他们这样做”的列表?

最佳答案

这是 Borland C++ Builder 字符串(不是标准 C++ 的 std::string)。

这样做是为了让您可以创建几乎所有类型的字符串,如 this Borland C++ Builder Strings reference提及:

The AnsiString class provides a lot of constructors that allow you to create a string of any kind. For example you can use it to declare:

An integer:

AnsiString Int = 120;

正如 RemyLebeau 所说:请注意 String 不是实际类型,它是 AnsiString(C++Builder 2007 及更早版本)或 的别名UnicodeString(C++Builder 2009 及更高版本)。两者都实现了数字类型的隐式转换。

关于C++ Builder 允许将字符串与 Int 进行比较 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53671394/

相关文章:

c++ - 包含 Commdlg.h 后打开未定义的文件名?

c++ - 关于何时在私有(private)成员变量上实现访问器而不是将它们公开的实践

java - 烦人的小问题——非法开始表达

c - 在 if 语句中使用 strcmp

c++ - 当我的程序是 "Not Responding"时,为什么我的 paintBox Canvas 被删除?

c++ - multi_index 模板编译错误

c++ - 相互比较文本文件的元素

c - 有没有办法让 sprintf() 在以整数作为输入时不删除 0?

c++ - 将 Linux 打开、读取、写入、关闭功能转换为在 Windows 上工作

delphi - 如何打印到 C++Builder 输出窗口