In this case w++ and w = w + 1 is not same. Please tell me the reason. Problem is coloured.
using System;
class Widget
{
public int _value;
public static Widget operator +(Widget a, Widget b)
{
// Add two Widgets together.
// ... Add the two int values and return a new Widget.
Widget widget = new Widget();
widget._value = a._value + b._value;
return widget;
}
public static Widget operator ++(Widget w)
{
// Increment this widget.
w._value++;
return w;
}
}
class Program
{
static void Main()
{
// Increment widget twice.
Widget w = new Widget();
w++;
Console.WriteLine(w._value);//1
w++;
Console.WriteLine(w._value);//2
// Create another widget.
Widget g = new Widget();
g++;
Console.WriteLine(g._value);//1
// Add two widgets.
Widget t = w + g;
Console.WriteLine(t._value);//3
Console.Read();
}
}
/*
1
2
1
3
*/
Loading
Posted Feb 22, 2014, 2:59 PM
VulpesPosted Feb 21, 2014, 4:28 PM
Note that in C# only certain operators can be overloaded and some operators have to be overloaded in pairs i.e. if you overload one, you have to overload the other (== and != for example).
+ and ++ are regarded as separate operators.
+ is a binary operator (requires two operands) and ++ is a unary operator (requires only one operand). There's also a unary version of the + operator (for example +6) which can be overloaded separately.
So, you can overload these operators how you see fit but, hopefully, in a way which you or your users will find intuitive.
Posted Feb 21, 2014, 4:08 PM
When to use one positive sign?
When to use two positive signs?
Problem is highlighted.
public static Widget operator +(Widget a, Widget b)
public static Widget operator ++(Widget w)
Posted Feb 20, 2014, 9:20 AM
VulpesPosted Feb 19, 2014, 11:21 AM
However, when you move to operator overloading for arbitrary classes, this is not necessarily the case as you are free to redefine these operators individually and independently.
Of course, with freedom comes responsibility. If you are writing a library for other people to use which features operator overloading, then operators should ideally have the effect which your users expect them to have. If they don't, then your library may not be too popular!
Posted Feb 19, 2014, 9:09 AM
VulpesPosted Feb 18, 2014, 5:15 PM
It just adds one widget to another.
The overloading of the ++ operator is consistent with + in that it increments the _value field of the Widget object.
So, if you add the highlighted code, it will work as expected when you use w + 1 or 1 + w: