我最近开始研究使用 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/