Guide to the Language


CHAPTER 22 Operator Overloading


Download 2 Mb.
Pdf ko'rish
bet55/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   51   52   53   54   55   56   57   58   ...   78
Bog'liq
C sharp

CHAPTER 22
Operator Overloading
Operator overloading allows operators to be redefined and used where one 
or both of the operands are of a certain class. When done correctly, this 
can simplify the code and make user-defined types as easy to use as the 
simple types.
 Operator Overloading Example
In this example, there is a class called MyNum with an integer field and a 
constructor for setting that field. There is also a static Add method that adds 
two MyNum objects together and returns the result as a new MyNum object.
class MyNum
{
public int val;
public MyNum(int i) { val = i; }
public static MyNum Add(MyNum a, MyNum b) {
return new MyNum(a.val + b.val);
}
}
Two MyNum instances can be added together using the Add method.
MyNum a = new MyNum(10), b = new MyNum(5);
MyNum c = MyNum.Add(a, b);


130
 Binary Operator Overloading
What operator overloading does is simplify this syntax and thereby 
provide a more intuitive interface for the class. To convert the Add method 
to an overload method for the addition sign, replace the name of the 
method with the operator keyword followed by the operator that is to be 
overloaded. The whitespace between the keyword and the operator can 
optionally be left out. Note that for an operator overloading method to 
work, it must be defined as both public and static.
class MyNum
{
public int val;
public MyNum(int i) { val = i; }
public static MyNum operator +(MyNum a, MyNum b) {
return new MyNum(a.val + b.val);
}
}
Since the class now overloads the addition sign, this operator can be 
used to perform the desired calculation.
MyNum a = new MyNum(10), b = new MyNum(5);
MyNum c = a + b;
 Unary Operator Overloading
Addition is a binary operator, because it takes two operands. To overload a 
unary operator, such as increment (++), a single method parameter is
used instead.
Chapter 22 OperatOr OverlOading


131
public static MyNum operator ++(MyNum a)
{
return new MyNum(a.val + 1);
}
Note that this will overload both the postfix and prefix versions of the 
increment operator.
MyNum a = new MyNum(10);
a++;
++a;

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   51   52   53   54   55   56   57   58   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling