[英]Operator overloading compiles in Visual Studio 2013 but not gcc
I have a class where I am overloading the << and + operators like this: 我有一个类,我正在重载<<和+运算符,如下所示:
friend MyObject operator+(MyObject lhs, MyObject rhs){
MyObject obj;
obj.Property = lhs.Property + rhs.Property;
return obj;
}
friend std::ostream& operator<<(std::ostream& os, MyObject& n) {
os << MyObject.Property; //property is a double
return os;
}
This compiles in both Visual Studio and gnu++98 with no problems. 这在Visual Studio和gnu ++ 98中编译都没有问题。 I can also call them like this without any problems: 我也可以这样称呼他们没有任何问题:
MyObject obj1, obj2;
obj1.PutInValidState();
cout << obj1;
obj1 = obj1 + obj2;
However, when I call them at the same time like this: 但是,当我同时打电话给他们时:
cout << obj1 + obj2;
Visual Studio will compile it (and gives the correct output), but gnu++98 gives me the error "no match for 'operator<<' in ' std::operator<<(std::basic_ostream&, const char*)". Visual Studio将编译它(并提供正确的输出),但是gnu ++ 98在'std :: operator <<(std :: basic_ostream&,const char *)中给出了错误“'匹配'运算符<<' 。 I can get it to compile in both by adding const to the parameter in the function definition like this: 我可以通过在函数定义中的参数中添加const来编译它,如下所示:
friend std::ostream& operator<<(std::ostream& os, const MyObject& n) {
What is going on here? 这里发生了什么? Why do I need the const to make it work in gnu++98 but not in Visual Studio? 为什么我需要使const在gnu ++ 98中工作而在Visual Studio中不工作?
cout << obj1 + obj2;
is syntax sugar for 是语法糖
operator<<(cout, operator+(obj1,obj2));
here you can see that the n
parameter in your operator<<() overload is being bound to the value being returned by operator+(), which is a temporary object. 在这里你可以看到运算符<<()重载中的n
参数被绑定到operator +()返回的值,这是一个临时对象。 Now, in C++, there's a rule that non-const reference parameters can not bind to temporaries, which is why it won't compile in gcc. 现在,在C ++中,有一个规则,即非const引用参数不能绑定到temporaries,这就是为什么它不能在gcc中编译。
Visual studio, on the other hand, has a language extension which allows non-const reference parameters to bind to temporaries. 另一方面,Visual Studio具有语言扩展,允许非const引用参数绑定到临时对象。 I wish it didn't, since that extension is one of the ones that has bitten me when porting code to other compilers. 我希望它没有,因为那个扩展是在将代码移植到其他编译器时困扰我的那个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.