1 /// <summary>
2 /// 运算符重载实例
3 /// </summary>
4 public class OperatorOverloading
5 {
6
7 public class AddClass1
8 {
9 public int val;
10
11 /// <summary>
12 /// +运算符重载
13 /// </summary>
14 /// <param name="op1"></param>
15 /// <param name="op2"></param>
16 /// <returns></returns>
17 public static AddClass1 operator +(AddClass1 op1, AddClass1 op2)
18 {
19 AddClass1 returnVal = new AddClass1();
20 returnVal.val = op1.val + op2.val;
21 return returnVal;
22 }
23 /// <summary>
24 /// -运算符重载
25 /// </summary>
26 /// <param name="op1"></param>
27 /// <param name="op2"></param>
28 /// <returns></returns>
29 public static AddClass1 operator -(AddClass1 op1, AddClass1 op2)
30 {
31 AddClass1 returnVal = new AddClass1();
32 returnVal.val = op1.val - op2.val;
33 return returnVal;
34 }
35
36 }
37
38
39 }
40
41
42调用方法:
43
44 OperatorOverloading.AddClass1 op1 = new OperatorOverloading.AddClass1();
45 OperatorOverloading.AddClass1 op2 = new OperatorOverloading.AddClass1();
46 OperatorOverloading.AddClass1 op3 = new OperatorOverloading.AddClass1();
47 op1.val = 5;
48 op2.val = 6;
49 op3 = op1 + op2;
50 op3 =op3 - op2;
51
2 /// 运算符重载实例
3 /// </summary>
4 public class OperatorOverloading
5 {
6
7 public class AddClass1
8 {
9 public int val;
10
11 /// <summary>
12 /// +运算符重载
13 /// </summary>
14 /// <param name="op1"></param>
15 /// <param name="op2"></param>
16 /// <returns></returns>
17 public static AddClass1 operator +(AddClass1 op1, AddClass1 op2)
18 {
19 AddClass1 returnVal = new AddClass1();
20 returnVal.val = op1.val + op2.val;
21 return returnVal;
22 }
23 /// <summary>
24 /// -运算符重载
25 /// </summary>
26 /// <param name="op1"></param>
27 /// <param name="op2"></param>
28 /// <returns></returns>
29 public static AddClass1 operator -(AddClass1 op1, AddClass1 op2)
30 {
31 AddClass1 returnVal = new AddClass1();
32 returnVal.val = op1.val - op2.val;
33 return returnVal;
34 }
35
36 }
37
38
39 }
40
41
42调用方法:
43
44 OperatorOverloading.AddClass1 op1 = new OperatorOverloading.AddClass1();
45 OperatorOverloading.AddClass1 op2 = new OperatorOverloading.AddClass1();
46 OperatorOverloading.AddClass1 op3 = new OperatorOverloading.AddClass1();
47 op1.val = 5;
48 op2.val = 6;
49 op3 = op1 + op2;
50 op3 =op3 - op2;
51