利用现有运算符,针对自定义类或结构,简化地自定义某运算操作,一般选用有相关性的既有运算符
操作数至少有一个是类或结构
不能改变运算符优先级
不能重载的运算符: =,&&,||,[],()等
class Program { static void Main(string[] args) { Pet P = new Dog("pp"); P++;//++有了重载定义的计算方式 P.ShowAge(); } } abstract public class Pet { protected string Name; public Pet(string name) { Name = name; } public void PrintName() { Console.WriteLine("Print" + Name); } abstract public void Speak(); } abstract public class Pet { protected string Name; protected int Age; public Pet(string name) { Name = name; Age = 0; } public void PrintName() { Console.WriteLine("Print" + Name); } public static Pet operator ++(Pet pet)//重载运算符++//针对类Pet { ++pet.Age; return pet; } public void ShowAge() { Console.WriteLine(Name+ " Age = " + Age); } abstract public void Speak(); } public class Dog : Pet { static int Num; static Dog() { Num = 0; } public Dog(string name) : base(name) { ++Num; } new public void PrintName() { Console.WriteLine("子print名字是 " + base.Name); } { Console.WriteLine("子说,我是狗狗 " + Name); } static public void ShowNum() { Console.WriteLine("Dog's number = " + Num); } public void Lost() { --Num; Console.WriteLine(Name + " is Lost!"); } }