【发布时间】:2013-12-21 06:34:51
【问题描述】:
我有这个代码:
#include <iostream>
using namespace std;
int main()
{
string name = "John ";
int age = 32;
name += age;
cout << name << endl;
return 0;
}
代码编译成功,但在运行时背叛,因为它默默地忽略了连接部分并打印:
John
我知道我们需要使用 stringstream 来完成任务。但是为什么上面的代码会编译呢? 因为下面的代码:
#include <iostream>
using namespace std;
int main()
{
string name = "John ";
int age = 55;
name = name + age;
cout << name << endl;
return 0;
}
适当地抛出错误:
错误:“姓名+年龄”中的“操作员+”不匹配
我从 Java 知道 a += b 与 a = a + b 不同,因为前者将结果类型转换为 a 的类型。 Reference。但我认为这在 C++ 中并不重要,因为我们总是可以这样做:
int a = 1;
float f = 3.33;
a = a + f;
无需担心与 Java 不同的精度警告可能丢失。需要在 C++ 中对此进行引用。
所以现在如果我们假设 name += age; 扩展为 name = string (name + age); 那么代码也不应该仅仅因为名称 + 年龄不合法而编译。
【问题讨论】:
-
你确定它忽略了串联吗?我得到
John 7,这是我所期望的,因为 55 是'7'的 ASCII 值。 -
另外,你的假设是错误的。对于类类型,
a += b不等于a = a+b。第一个使用operator+=,第二个使用operator+和operator=,这完全取决于类编写者如何实现这些运算符。 -
是的。但我知道字符串的 += 就像 a + b 一样工作。是的,它打印 John 7。我的机器上的 age = 32。错字。现在一切都清楚了。谢谢!
-
不损失精度?如果 a 是 int,那将如何发生?似乎 .33 不会使其 to 成为第一个运算符。你写的是‘a.operator=(a.+(f.operator int()))‘
-
我的意思是警告。更新它。感谢您指出。
标签: java c++ g++ type-conversion implicit-conversion