struct_Operator_Overloading.cs
1 using System; 2 3 namespace 运算符重载 4 { 5 /*----------< 结构体:struct_Operator_Overloading >----------- 6 * 运算符重载: 7 ----------------------------------------------------------------*/ 8 public struct struct_Operator_Overloading 9 { 10 public int nReal { get; set; } // 实数部分 11 public int nImaginary { get; set; } // 虚数部分 12 /*----------------------< 带参数构造函数 >------------------------ 13 * 1.带参数的构造函数(必须加上【:this()】否则会有如下错误提示: 14 * 错误 CS0188: 在给“this”对象的所有字段赋值之前,无法使用该对 15 * 象. 16 ---------------------------------------------------------------------*/ 17 public struct_Operator_Overloading(int real, int imaginary) : this() 18 { 19 nReal = real; 20 nImaginary = imaginary; 21 } 22 /*-------------------< 重载运算符【 + 】>--------------------- 23 * 重载运算符【 + 】: 24 * 1.形参a : 第一个操作数, 必须为struct_Operation_Overrloading类型 25 * 2.形参b : 第二个操作数. 必须为struct_Operation_Overrloading类型 26 * 3.返回值: 必须为 struct_Operation_Overrloading 类型 27 * 4.修饰词: 必须加 public 28 * 5.所有运算符重载的方法都应为静态方法: static 29 ----------------------------------------------------------------*/ 30 public static struct_Operator_Overloading operator +(struct_Operator_Overloading a, struct_Operator_Overloading b) 31 { 32 struct_Operator_Overloading result = new struct_Operator_Overloading(); 33 result.nReal = a.nReal + b.nReal; 34 result.nImaginary = a.nImaginary + b.nImaginary; 35 return result; // 返回结果 36 } 37 38 // 重写ToString()方法 39 public override string ToString() 40 { 41 return string.Format("{0}+{1}", nReal, nImaginary); 42 } 43 44 } 45 46 }
Program.cs
1 using System; 2 3 namespace 运算符重载 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 struct_Operator_Overloading a = new struct_Operator_Overloading(10, 20); 10 struct_Operator_Overloading b = new struct_Operator_Overloading(30, 40); 11 struct_Operator_Overloading sum = new struct_Operator_Overloading(); 12 // 利用重载的【+】来实现加法运算: 13 // 即: a与b的形参1与形参1相加; 形参2与形参2相加 14 sum = a + b; 15 16 Console.WriteLine(" sum.nReal = {0} sum.Imaginary = {1}", sum.nReal, sum.nImaginary); 17 //测试 : 重写的ToString()方法 18 Console.WriteLine(" sum.ToSting();{0} ", sum.ToString()); 19 20 Console.ReadLine(); 21 } 22 } 23 }