1 #define _CRT_SECURE_NO_WARNINGS
2 #include <iostream>
3 using namespace std;
4
5 class box
6 {
7 private:
8 int x;
9 int y;
10 int z;
11
12
13 public:
14 box() :x(10), y(20), z(30)
15 {
16
17 }
18
19 friend box operator +(const box &box1, const box &box2);
20 friend box operator +(const box &box1, int num);
21 friend ostream & operator << (ostream &, const box &box1);
22 friend istream &operator >> (istream &, box &box1);
23
24 void show()
25 {
26 cout << x << y << z << endl;
27 }
28
29 };
30
31 //外部重载,没有this指针隐含对象
32 box operator +(const box &box1, const box &box2)
33 {
34 box tmp;
35 tmp.x = box1.x + box2.x;
36 tmp.y = box1.y + box2.y;
37 tmp.z = box1.z + box2.z;
38 return tmp;
39 }
40
41
42 box operator +(const box &box1, int num)
43 {
44 box tmp;
45 tmp.x = box1.x + num;
46 return tmp;
47 }
48
49
50 //重载流运算符,输入一个引用,返回一个引用
51 ostream & operator << (ostream &,const box &box1)
52 {
53 return cout << box1.x << box1.y << box1.z << endl;
54 }
55
56 istream &operator >> (istream &, box &box1)
57 {
58 return cin >> box1.x >> box1.y >> box1.z ;
59 }
60
61 void main()
62 {
63 box box1;
64 box box2;
65 box box3 = box1 + box2;
66 box box4 = box1 + 20;
67 /*box4.show();*/
68 cin >> box1;
69 cout << box1;
70 cin.get();
71 }