■ operator overloading
• Operator overloading gives the ability to use the same operator to do various operations.
• It allows you to define how operators work with your custom types (classes or structs).
• This can make your custom types more intuitive and easier to use.
Let's say we have a Complex class to represent complex numbers. We want to overload the + and - operators to add and subtract complex numbers.
Example :-
_____________________________
public class Complex
{
public double Real { get; }
public double Imaginary { get; }
public Complex(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
// Overloading the + operator
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
// Overloading the - operator
public static Complex operator -(Complex c1, Complex c2)
{
return new Complex(c1.Real - c2.Real, c1.Imaginary - c2.Imaginary);
}
// Overriding ToString method for better output representation
public override string ToString()
{
return $"{Real} + {Imaginary}i";
}
}
class Program
{
static void Main()
{
Complex c1 = new Complex(1.0, 2.0);
Complex c2 = new Complex(3.0, 4.0);
Complex sum = c1 + c2;
Complex difference = c1 - c2;
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Difference: {difference}");
}
}
_____________________________
Comments
Post a Comment