设计一个长方形类Triangle,包含长和宽两个私有数据成员。
要求重载运算符
·=
能够支持:对象=数值 普通变量=对象 对象=对象 支持连续的赋值
·+= :自定义加法功能
联系与=的联系
·> :实现比较两个矩形对象面积大小的比较
能够支持:两个对象的比较,对象和数字的比较,数字和对象的比较
·>> :实现矩形对象的输入
·<< :实现矩形对象的输出
1 #include <iostream>
2 using namespace std;
3
4 class Triangle
5 {
6 private:
7 double length;
8 double width;
9 public:
10 Triangle(double l = 0.0, double w = 0.0) : length(l), width(w) {}
11 ~Triangle() {}
12 Triangle(const Triangle& t) : length(t.length), width(t.width) {}
13 Triangle& operator =(const Triangle& t)
14 {
15 if (this != &t)
16 {
17 length = t.length;
18 width = t.width;
19 }
20 return *this;
21 }
22 Triangle& operator =(double d)
23 {
24 length = width = d;
25 return *this;
26 }
27 operator double ()
28 {
29 return length * width;
30 }
31 Triangle& operator +=(const Triangle& t)
32 {
33 length += t.length;
34 width += t.width;
35 return *this;
36 }
37 friend bool operator > (const Triangle& lhs, const Triangle& rhs);
38 friend bool operator > (const Triangle& lhs, double rhs);
39 friend bool operator > (double lhs, const Triangle& rhs);
40 friend istream& operator >>(istream& in, Triangle& rhs);
41 friend ostream& operator <<(ostream& out, const Triangle& rhs);
42 };
43
44 bool operator >(const Triangle& lhs, const Triangle& rhs)
45 {
46 return lhs.length * lhs.width > rhs.length * rhs.width;
47 }
48
49 bool operator >(const Triangle& lhs, double rhs)
50 {
51 return lhs.length * lhs.width > rhs;
52 }
53
54 bool operator >(double lhs, const Triangle& rhs)
55 {
56 return lhs > rhs.length * rhs.width;
57 }
58
59 istream& operator >>(istream& in, Triangle& rhs)
60 {
61 in >> rhs.length >> rhs.width;
62 if (!in)
63 {
64 cerr << "Input error!" << endl;
65 exit(1);
66 }
67 return in;
68 }
69
70 ostream& operator <<(ostream& out, const Triangle& rhs)
71 {
72 out << rhs.length << '\t' << rhs.width;
73 return out;
74 }
75
76 Triangle& operator +(const Triangle& lhs, const Triangle& rhs)
77 {
78 Triangle tmp(lhs);
79 return tmp += rhs;
80 }
81
82 int main()
83 {
84 Triangle t1(1.0, 2.0);
85 Triangle t2;
86 t1 = t2;
87
88 cin >> t1 >> t2;
89 cout << t1 << endl;
90 cout << t2 << endl;
91
92 t1 = t2;
93 cout << t1 << endl;
94 cout << t2 << endl;
95
96 t1 = 10.0;
97 cout << t1 << endl;
98 double d = 0.0;
99 d = t1;
100 cout << d << endl;
101
102 cout << (t1 > t2) << endl;
103 cout << (t1 > 5.0) << endl;
104 cout << (5.0 > t1) << endl;
105
106 t1 += t2;
107 cout << t1 << endl;
108 cout << t2 << endl;
109
110 return 0;
111 }
posted on 2011-04-29 00:40
unixfy 阅读(200)
评论(0) 编辑 收藏 引用