运算符重载和自定义类型变换.pptVIP

  • 0
  • 0
  • 约3.48千字
  • 约 30页
  • 2019-10-31 发布于福建
  • 举报
;运算符重载;;;可重载的运算符; public class Complex { public int real; public int imaginary; public Complex(){ } public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static Complex operator +(Complex c1, Complex c2) { return new Complex(c1.real+c2.real, c1.imaginary +c2.imaginary); } public static Complex operator -(Complex c1, Complex c2) { return new Complex(c1.real-c2.real, c1.imaginary -c2.imaginary); } public override string ToString(){ return(String.Format({0} + {1}i, real, imaginary)); } }; public static void Main() { Complex num1 = new Complex(3, 4); Complex num2 = new Complex(3, 4); Complex num3 = new Complex(-3, 4); Complex sum = num1.Add(num2); Complex result = num1 + num2 - num3; Console.WriteLine(First complex number: {0}, num1); Console.WriteLine(Second complex number: {0}, num2); Console.WriteLine(The sum of the two numbers: {0}, sum); Console.WriteLine(The result: {0}, result); Console.WriteLine(num1==num2); Console.Read(); }; public static bool operator ==(Complex c1, Complex c2) { if (c1.real == c2.real c1.imaginary == c2.imaginary) return true; else return false; } public static bool operator !=(Complex c1, Complex c2) { if (c1.real == c2.real c1.imaginary == c2.imaginary) return false; else return true; };重写Equals和GetHashCode方法;GetHashCode; public static bool operator ==(Complex c1, Complex c2) { if (c1.real == c2.real c1.imaginary == c2.imaginary) return true; else return false; } public static bool operator !=(Complex c1, Complex c2) { if (

文档评论(0)

1亿VIP精品文档

相关文档