VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#中运算符的重载

在C#中,运算符的重载是指允许我们自定义某些运算符的行为。这可以通过在类中定义特殊的方法来实现。以下是一个简单的实例代码讲解:
 

using System;
 
class ComplexNumber
{
    public double Real { get; set; }
    public double Imaginary { get; set; }
 
    public ComplexNumber(double real, double imaginary)
    {
        Real = real;
        Imaginary = imaginary;
    }
 
    // 重载加法运算符
    public static ComplexNumber operator +(ComplexNumber a, ComplexNumber b)
    {
        return new ComplexNumber(a.Real + b.Real, a.Imaginary + b.Imaginary);
    }
 
    // 重载减法运算符
    public static ComplexNumber operator -(ComplexNumber a, ComplexNumber b)
    {
        return new ComplexNumber(a.Real - b.Real, a.Imaginary - b.Imaginary);
    }
 
    // 重载乘法运算符
    public static ComplexNumber operator *(ComplexNumber a, ComplexNumber b)
    {
        double real = a.Real * b.Real - a.Imaginary * b.Imaginary;
        double imaginary = a.Real * b.Imaginary + a.Imaginary * b.Real;
        return new ComplexNumber(real, imaginary);
    }
 
    // 重载除法运算符
    public static ComplexNumber operator /(ComplexNumber a, ComplexNumber b)
    {
        double denominator = b.Real * b.Real + b.Imaginary * b.Imaginary;
        double real = (a.Real * b.Real + a.Imaginary * b.Imaginary) / denominator;
        double imaginary = (a.Imaginary * b.Real - a.Real * b.Imaginary) / denominator;
        return new ComplexNumber(real, imaginary);
    }
 
    public override string ToString()
    {
        return $"({Real} + {Imaginary}i)";
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        ComplexNumber a = new ComplexNumber(3, 2);
        ComplexNumber b = new ComplexNumber(1, 7);
 
        Console.WriteLine("a + b = " + (a + b)); // 输出:a + b = (4 + 9i)
        Console.WriteLine("a - b = " + (a - b)); // 输出:a - b = (2 - 5i)
        Console.WriteLine("a * b = " + (a * b)); // 输出:a * b = (-11 + 23i)
        Console.WriteLine("a / b = " + (a / b)); // 输出:a / b = (0.29411764705882354 - 0.35294117647058826i)
    }
}
 
在这个例子中,我们定义了一个名为`ComplexNumber`的类,用于表示复数。我们为这个类重载了加法、减法、乘法和除法运算符,以便我们可以使用这些运算符来操作复数对象。


最后,如果你对python语言还有任何疑问或者需要进一步的帮助,请访问https://www.xin3721.com 本站原创,转载请注明出处:https://www.xin3721.com/ArticlecSharp/c47926.html

相关教程