defining operator + , = and +=
I once read the following statement from a C++ notes,
In C++, defining operator + and = does not give the right meaning to +=. This language-design bug is fixed in C#
I woul开发者_运维百科d like to know what exactly does this statement want to say? Is that related to operator overload?
I prefer C++ operator overloading mechanism. It definitely not a design bug according to me.
+
, =
and +=
are three different operators. If you want to use +=
you need to overload +=
. Overloading +
and =
won't make +=
work.
I would like to add that in E1 += E2
E1
gets evaluated only once as far as C++ is concerned. I don't know the exact rules in C#.
It says, that in C# if you have overloaded operator + C# automatically will emulate operator += as combination of + and = (a=a+b
is equal to a+=b
). In C++ it's not implemented, but it's not a bug. In C++ + and = doesn't give you += because mostly += works faster than +, because there is no need to create one more object.
That's why mostly operator + is writen using += operator. Consider fallowing code:
class foo
{
public:
foo& operator+=(const foo& rhs)
{
//.......
}
};
const foo operator+(const foo& lhs,const foo& rhs)
{
foo temp = lhs;
return temp+= rhs;
}
It means that in C++ if you defined your own operator +
and operator =
for your class, that still does not mean that your class will automatically support the +=
operator. If you want the +=
operator to work for your class, you have to define the +=
explicitly and separately.
In C#, if I understood it correctly, defining operators +
and =
for your class will also mean that you'll be able to use operator +=
with your class. The +=
will be "emulated" through combination of operator +
and operator =
. E.g. expression a += b
will be interpreted as a = a + b
.
It doesn't work that way in C++. If you don't define the +=
explicitly, a += b
will result in compiler error, even if you have +
and =
defined.
C# does not allow operator overloading = since it does not allow direct pointer management. Its behavior is fixed based on whether it is reference or value type. For the same reason you cannot overload += . It's meaning will always be doing the sum and assignment. You can only therefore decide what the meaning for + is to your datastructure.
精彩评论