[C#] C#演示用户定义的类如何能够重载运算符 →→→→→进入此内容的聊天室

来自 , 2020-12-07, 写在 C#, 查看 152 次.
URL http://www.code666.cn/view/3c3c139b
  1.  
  2. // complex.cs
  3. using System;
  4.  
  5. public struct Complex
  6. {
  7.    public int real;
  8.    public int imaginary;
  9.  
  10.    public Complex(int real, int imaginary)
  11.    {
  12.       this.real = real;
  13.       this.imaginary = imaginary;
  14.    }
  15.  
  16.    // 声明要重载的运算符 (+)、
  17.    // 可相加的类型(两个 Complex 对象)以及
  18.    // return type (Complex):
  19.    public static Complex operator +(Complex c1, Complex c2)
  20.    {
  21.       return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
  22.    }
  23.    // 重写 ToString 方法,从而以适当的格式显示复数:
  24.    public override string ToString()
  25.    {
  26.       return(String.Format("{0} + {1}i", real, imaginary));
  27.    }
  28.  
  29.    public static void Main()
  30.    {
  31.       Complex num1 = new Complex(2,3);
  32.       Complex num2 = new Complex(3,4);
  33.  
  34.       // 通过重载的加号运算符
  35.       // 将两个 Complex 对象(num1 和 num2)相加:
  36.       Complex sum = num1 + num2;
  37.  
  38.      // 使用重写的 ToString 方法打印数字以及相加得到的和:
  39.       Console.WriteLine("First complex number:  {0}",num1);
  40.       Console.WriteLine("Second complex number: {0}",num2);
  41.       Console.WriteLine("The sum of the two numbers: {0}",sum);
  42.  
  43.    }
  44. }
  45.  
  46.  
  47.  
  48. //csharp/4919

回复 "C#演示用户定义的类如何能够重载运算符"

这儿你可以回复上面这条便签

captcha