Overloaded operators work with user defined or basic data type depending upon the type of operands. It gives the ability to use the same operator to do various functionality. Operator overloading allows the user to give additional meaning to most operators so that it can be used with the user'sown data types, thereby making the data type easier to use.
Operator overloading, similar to function name overloading, helps to reduce the need for unusual function name making code easier to understand. It also supports programmer-controlled automatic type conversion, which blend user data types, appear and works in the same way as fundamental datatype provided by the c# language.
Syntax
Return-access-specifier class-name operator operator-name(parameters)
{
// Code
}
Here below the code to explain the operator overloading. Below there is one Program class and having two constructor and one operator overloading function and one display method to display the results.
Operator overloading, similar to function name overloading, helps to reduce the need for unusual function name making code easier to understand. It also supports programmer-controlled automatic type conversion, which blend user data types, appear and works in the same way as fundamental datatype provided by the c# language.
Syntax
Return-access-specifier class-name operator operator-name(parameters)
{
// Code
}
Here below the code to explain the operator overloading. Below there is one Program class and having two constructor and one operator overloading function and one display method to display the results.
Here below the main function in which create three instance of program object and then add first two object and set the result in third object. At last it display them all the object.
Output
The first one is the result of num1, second one is num2 and third one is num3. So Num3 is the add the first and second by adding object
Analyse
Adding of object is called operator overloading. We can overload the operator by using other symbol just like (-, *, ~, ==, !=, &&, ||)
Overloadable Operators
C# provides a wide variety of operators to perform operation on various operands. The operators are classified into urany and binary operation based on the number of arguments on which they operate. C# provide almost all operators to be overloaded in which case atleast one operand must be an instance of a class. It allow overloading of operation listed below table.
Operator Category | Operators |
---|---|
Arithmetic | +, -, *, /, % |
Bit-wise | &, |, ~, ^ |
Logical | &&, ||, ! |
Relational | >, <, ==, !=, <=, >= |
Assignment or Initialization | = |
Arithmetic Assignment | +=, -=, *=, /=, %=, &=, |=, ^= |
Shift | <<, >>, <<=, >>= |
Unary | ++, -- |
Subscripting | [] |
Function Call | () |
Dereferencing | -> |
Urany Sign Prefix | +, - |
Allocate and Free | new, delete |
No comments:
Post a Comment