可能重复:
Is it a bug that Microsoft VS C++ compiler can Initialize a reference from a temporary object为什么临时对象的引用在这里有效?
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
string a;
public:
test(string b){a=b;}
friend string operator+(test);
};
string operator+(string &c,test a)
{
c=c+a.a;
return c;
}
void main()
{
test d("the ");
test e("world!");
string s="Hello ";
s=s+d+e;
cout<<s<<endl;
}
第二最后一行S = S + d + E;在第一个重载操作符+它返回一个临时对象后,第二个重载操作符+意外地工作!但是operator +函数的第一个参数是一个引用。为什么临时对象的引用在这里是有效的,或者有我错过的东西?
P.S:它是由VC++ 6.0编译的,这里是运行结果。
自从语言标准化之前,这是MS编译器支持的“扩展”。 VS2010对此提出警告。 – 2012-04-10 12:28:37
对不起,我没有看到任何临时对象。临时对象在哪里? – 2012-04-10 12:29:26
@MrLister:仔细观察 - 这里使用的'operator +'返回值 - 所以它确实是一个临时的。 – 2012-04-10 12:30:21