标签:style blog http color ar 2014 div sp log
运算符重载要求:
重载的实例为:
要定义重载的类中定义如下:
1 class LimitedInt 2 { 3 const int MaxValue = 100; 4 const int MinValue = 0; 5 6 public static LimitedInt operator -(LimitedInt x) 7 { 8 LimitedInt li = new LimitedInt(); 9 li.TheValue = -x.TheValue; 10 return li; 11 } 12 public static LimitedInt operator -(LimitedInt x,double y) 13 { 14 LimitedInt li = new LimitedInt(); 15 li.TheValue = x.TheValue - (int)y; 16 return li; 17 } 18 19 private int _TheValue = 0; 20 public int TheValue 21 { 22 get 23 { 24 return _TheValue; 25 } 26 set 27 { 28 _TheValue = value; 29 } 30 } 31 }
可见,第一个重载的运算符是单目运算符,-号
第二个还是 -号,但是是双目运算符。
此时可以做如下调用:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 LimitedInt x = new LimitedInt(); 6 x.TheValue = 13; 7 8 double y = 7; 9 10 LimitedInt li = new LimitedInt(); 11 12 li =x-y; 13 14 Console.WriteLine("{0}",li.TheValue); 15 16 li = -x; 17 18 Console.WriteLine("{0}",li.TheValue); 19 20 Console.ReadKey(); 21 } 22 }
输出为6和-13,可见操作正确。
标签:style blog http color ar 2014 div sp log
原文地址:http://www.cnblogs.com/lhyz/p/3976041.html