运算符重载示例

  1. public struct Complex 
  2. {
  3.     public double real;
  4.     public double imaginary;
  5.   
  6.     public Complex(double real, double imaginary) 
  7.     {
  8.         this.real = real;
  9.         this.imaginary = imaginary;
  10.     }
  11.     public static Complex operator + (Complex c1) 
  12.     {
  13.         return c1;
  14.     }
  15.     public static Complex operator - (Complex c1) 
  16.     {
  17.         return new Complex(-c1.real , -c1.imaginary);
  18.     }
  19.     public static bool operator true (Complex c1) 
  20.     {
  21.         return c1.real !=0 || c1.imaginary != 0;
  22.     }
  23.     public static bool operator false (Complex c1) 
  24.     {
  25.         return c1.real ==0 && c1.imaginary == 0;
  26.     }
  27.     public static Complex operator + (Complex c1, Complex c2) 
  28.     {
  29.         return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
  30.     }
  31.     public static Complex operator - (Complex c1, Complex c2) 
  32.     {
  33.         return c1 + (- c2 );
  34.     }
  35.     public static Complex operator * (Complex c1, Complex c2) 
  36.     {
  37.         return new Complex( c1.real * c2.real - c1.imaginary * c2.imaginary,
  38.             c1.real * c2.imaginary + c1.imaginary * c2.real );
  39.     }
  40.     public static Complex operator * (Complex c, double k )
  41.     {
  42.         return new Complex( c.real * k, c.imaginary * k );
  43.     }
  44.     public static Complex operator *( double k, Complex c )
  45.     {
  46.         return c * k;
  47.     }
  48.   
  49.     public override string ToString()
  50.     {
  51.         return(System.String.Format("({0} + {1} i)", real, imaginary));
  52.     }
  53.   
  54.     public static void Main() 
  55.     {
  56.         Complex num1 = new Complex(2,3);
  57.         Complex num2 = new Complex(3,4);
  58.   
  59.         Complex result = num1 ? - num1 * 5 + num1 * num2  :  new Complex(0,0);
  60.   
  61.         System.Console.WriteLine("First complex number:  {0}", num1);
  62.         System.Console.WriteLine("Second complex number: {0}", num2);
  63.         System.Console.WriteLine("The result is: {0}", result);
  64.     }
  65. }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值