Operator overloading
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
classBox
{
privatedoublelength; // Length of a box
privatedoublebreadth; // Breadth of a box
privatedoubleheight; // Height of a box
publicdoublegetVolume()
{
returnlength * breadth * height;
}
publicvoidsetLength(doublelen)
{
length = len;
}
publicvoidsetBreadth(doublebre)
{
breadth = bre;
}
publicvoidsetHeight(doublehei)
{
height = hei;
}
// Overload + operator to add two Box objects.
publicstaticBoxoperator +(Box b, Box c)
{
Boxbox = newBox();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
returnbox;
}
}
classTester
{
staticvoidMain(string[] args)
{
Box Box1 = newBox(); // Declare Box1 of type Box
Box Box2 = newBox(); // Declare Box2 of type Box
Box Box3 = newBox(); // Declare Box3 of type Box
doublevolume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
Console.ReadKey();
}
}
Output:
publicclassWidget
{
publicint_value;
publicstaticWidgetoperator +(Widget a, Widget b)
{
// Add two Widgets together.
// ... Add the two int values and return a new Widget.
Widgetwidget = newWidget();
widget._value = a._value + b._value;
returnwidget;
}
publicstaticWidgetoperator ++(Widget w)
{
// Increment this widget.
w._value++;
returnw;
}
}
classProgram
{
staticvoidMain()
{
// Increment widget twice.
Widgetw = newWidget();
w++;
Console.WriteLine(w._value);
w++;
Console.WriteLine(w._value);
// Create another widget.
Widgetg = newWidget();
g++;
Console.WriteLine(g._value);
// Add two widgets.
Widgett = w + g;
Console.WriteLine(t._value);
Console.ReadKey();
}
}
Output:
No comments:
Post a Comment
Thank you for visiting my blog