c#

C#重载运算符的实际应用案例分享

小樊
84
2024-08-21 13:04:28
栏目: 编程语言

  1. 向量相加:可以通过重载加号运算符来实现向量的相加操作。
public class Vector
{
    public int X { get; set; }
    public int Y { get; set; }

    public Vector(int x, int y)
    {
        X = x;
        Y = y;
    }

    public static Vector operator +(Vector v1, Vector v2)
    {
        return new Vector(v1.X + v2.X, v1.Y + v2.Y);
    }
}

class Program
{
    static void Main()
    {
        Vector v1 = new Vector(1, 2);
        Vector v2 = new Vector(3, 4);

        Vector result = v1 + v2;

        Console.WriteLine($"Result: ({result.X}, {result.Y})"); // Output: Result: (4, 6)
    }
}
  1. 自定义数据类型相加:可以通过重载加号运算符来实现自定义数据类型的相加操作。
public class ComplexNumber
{
    public int Real { get; set; }
    public int Imaginary { get; set; }

    public ComplexNumber(int real, int imaginary)
    {
        Real = real;
        Imaginary = imaginary;
    }

    public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
    {
        return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }
}

class Program
{
    static void Main()
    {
        ComplexNumber c1 = new ComplexNumber(1, 2);
        ComplexNumber c2 = new ComplexNumber(3, 4);

        ComplexNumber result = c1 + c2;

        Console.WriteLine($"Result: {result.Real} + {result.Imaginary}i"); // Output: Result: 4 + 6i
    }
}

这些例子展示了如何通过重载运算符来实现自定义数据类型的特定操作,使代码更加简洁和易于理解。

0
看了该问题的人还看了