运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
要重载运算符需要使用 operator关键字,并且要使用访问修饰符static修饰。如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication3 7 { 8 class Program 9 { 10 public class Sum 11 { 12 #region Members 13 public int num1; 14 public int num2; 15 #endregion 16 17 #region Constructor 18 public Sum(int number1,int number2) 19 { 20 this.num1 = number1; 21 this.num2 = number2; 22 } 23 #endregion 24 25 #region Operator 26 public static Sum operator +(Sum sum1,Sum sum2) 27 { 28 return new Sum(sum1.num1+sum2.num1,sum2.num2+sum1.num2); 29 } 30 #endregion 31 32 33 } 34 static void Main(string[] args) 35 { 36 Sum sumFirst=new Sum(5,6); 37 Sum sumSecond=new Sum(6,5); 38 Sum sumThird = sumFirst + sumSecond; 39 40 Console.WriteLine("sumThird.num1={0},sumThird.num2={0}",sumThird.num1,sumThird.num2); 41 Console.ReadKey(); 42 } 43 } 44 }
运行结果为: