类的操作符重载学习实例时间:2022-10-07 17:45:19一直听到重载,但用得多都是函数重载,对于操作符重载,基本上没用过,因此也就没怎么关注过操作符重载怎么实现,今天看到一本《C#教程》上看到两个例子,觉得挺好懂的,记录下来。 一元操作符(++)重载 using System; class Player { public int neili; public int tili; public int jingyan; public int neili_r; public int tili_r; public Player() { neili=10; tili=50; jingyan=0; neili_r=50; tili_r=50; } //重载 public static Player operator++(Player p) { p.neili=p.neili+50; p.tili=p.tili+100; p.neili_r=p.neili; p.tili_r=p.tili; return p; } public void Show() { Console.WriteLine("Tili:{0}",tili); Console.WriteLine("Jingyan:{0}",jingyan); Console.WriteLine("Neili:{0}",neili); Console.WriteLine("Tili_full:{0}",tili_r); Console.WriteLine("Neili_fu:{0}",neili_r); } } class Test { public static void Main() { Player man=new Player(); man.Show(); //使用 man++; Console.WriteLine("Now upgrading..."); man.Show(); } } 二元操作符(+)重载 using System; class DKR { public int x,y,z; public DKR(int vx,int vy,int vz) { x=vx; y=vy; z=vz; } //重载 public static DKR operator+(DKR d1,DKR d2) { DKR dkr=new DKR(0,0,0); dkr.x=d1.x+d2.x; dkr.y=d1.y+d2.y; dkr.z=d1.z+d2.z; return dkr; } } class Test { public static void Main() { DKR d1=new DKR(3,2,1); DKR d2=new DKR(0,6,5); //使用 DKR d3=d1+d2; Console.WriteLine("The 3d location of d3 is:{0},{1},{2}",d3.x,d3.y,d3.z); } }