面向对象实验二(运算符重载)

一、实验目的
1、掌握成员函数重载运算符。
2、掌握友元函数重载运算符。
3、理解并掌握引用在运算符重载中的作用。

二、实验内容
1、定义空间中的点类(有x,y,z坐标),并重载其++和—运算符。编写主函数对该类进行应用。

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class Point
 5 {
 6 private:
 7     int x,y,z;
 8 public:
 9     Point(int a=0,int b=0,int c=0);
10     Point operator ++();
11     Point operator ++(int);
12     Point operator --();
13     Point operator --(int);
14     void print();
15 };
16 
17 int main()
18 {
19     Point ob1(2,3,4),ob2;
20     ++ob1;
21     ob1.print();
22     ob2=ob1++;
23     ob2.print();
24     ob1.print();
25     --ob1;
26     ob1.print();
27     ob2=ob1--;
28     ob2.print();
29     ob1.print();
30     return 0;
31 }
32 
33 
34 Point::Point(int a, int b,int c)
35 {
36     x=a;
37     y=b;
38     z=c;
39 }
40 
41 void Point::print()
42 {
43     cout<<'('<<x<<','<<y<<','<<z<<')'<<endl;
44 }
45 
46 Point Point::operator ++()
47 {
48     ++x;
49     ++y;
50     ++z;
51     return *this;
52 }
53 
54 Point Point::operator ++(int)
55 {
56     Point temp=*this;
57     x++;
58     y++;
59     z++;
60     return temp;
61 }
62 
63 Point Point::operator --()
64 {
65     --x;
66     --y;
67     --z;
68     return *this;
69 }
70 
71 Point Point::operator --(int)
72 {
73     Point temp=*this;
74     x--;
75     y--;
76     z--;
77     return temp;
78 }

 

2、定义一个复数类,并通过定义运算符重载实现两个复数可以判别是否相等(==),并给出主函数应用该类。

 1 #include<iostream>
 2 #include<iomanip>
 3 using namespace std;
 4 
 5 class com
 6 {
 7     private:
 8     int real,imag;
 9     public:
10     com(int a,int b);
11     void operator ==(com b);
12 };
13 
14 
15 
16 int main()
17 {
18     com ob1(2.2,3.3),ob2(2.2,3.3);
19     ob1==ob2;
20     return 0;
21 }
22 
23 com::com(int a,int b)
24 {
25     real=a;
26     imag=b;
27 }
28 
29 void com::operator ==(com b)
30 {
31     if((real==b.real)&&(imag==b.imag))
32     {
33         cout<<"两复数相等!!"<<endl;
34     }
35     else
36     {
37         cout<<"两复数不相等!!"<<endl;
38     }
39 }