1、设计一个控制台应用程序,定义一个MyPoint类,该类能表示二维平面空间的点,完成点类及运算符重载等相关功能。具体要求如下:
(1)MyPoint类中定义2个私有字段x和y及相应的构造函数。
(2)MyPoint类中重载ToString方法输出坐标x和y的值。
(3)MyPoint类中重载一元运算符“-”。
(4)MyPoint类中重载二元运算符“+”和“-”。
(5)MyPoint类中重载二元运算符“>”和“<”。
(6)MyPoint类中重载二元运算符“==”和“!=”。
(7)在Main方法中测试上述运算符。
![]()
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace Myproject
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 Mypoint a = new Mypoint(1, 1);
14 Mypoint b = new Mypoint(1, 1);
15 Mypoint c = new Mypoint(2, 2);
16 Console.WriteLine( "Check: a+b " + (a + b) );
17 Console.WriteLine( "Check: a-b " + (a - b) );
18
19 Console.WriteLine( "Check: < , > , != , == " );
20 if (a < c) Console.WriteLine("a < c ");
21 if( c > a) Console.WriteLine("c > a" );
22
23 if( a + b != a)
24 {
25 Console.WriteLine("a + b != a");
26 }
27
28 if ( a + b == c)
29 {
30 Console.WriteLine("a + b == c");
31 }
32 }
33 }
34 public class Mypoint
35 {
36 int x, y;
37
38 public Mypoint(int x, int y)
39 {
40 this.x = x;
41 this.y = y;
42 }
43 public Mypoint() : this(0, 0) { }
44 public int X { get { return x; } set { x = value; } }
45 public int Y { get { return y; } set { y = value; } }
46 public override string ToString()
47 {
48 return string.Format("({0},{1})", x, y);
49 }
50
51 public static Mypoint operator - (Mypoint u)
52 {
53 Mypoint p = new Mypoint();
54 p.X = -u.X;
55 p.Y = -u.Y;
56 return p;
57 }
58
59 public static Mypoint operator + (Mypoint u, Mypoint v)
60 {
61 Mypoint p = new Mypoint();
62 p.X = u.X + v.X;
63 p.Y = u.Y + v.Y;
64 return p;
65 }
66
67 public static Mypoint operator -(Mypoint u, Mypoint v)
68 {
69 Mypoint p = new Mypoint();
70 p.X = u.X - v.X;
71 p.Y = u.Y - v.Y;
72 return p;
73 }
74
75 public static bool operator >(Mypoint u, Mypoint v)
76 {
77 bool status = false ;
78 if( u.X >= v.X && u.Y >= v.Y)
79 {
80 status = true;
81 }
82 return status;
83 }
84
85 public static bool operator <(Mypoint u, Mypoint v)
86 {
87 bool status = false;
88 if (u.X <= v.X && u.Y <= v.Y)
89 {
90 status = true;
91 }
92 return status;
93 }
94
95 public static bool operator ==(Mypoint u, Mypoint v)
96 {
97 bool status = false;
98 if (u.X == v.X && u.Y == v.Y)
99 {
100 status = true;
101 }
102 return status;
103 }
104
105 public static bool operator !=(Mypoint u, Mypoint v)
106 {
107 bool status = false;
108 if (u.X != v.X || u.Y != v.Y)
109 {
110 status = true;
111 }
112 return status;
113 }
114
115 }
116
117 }
View Code