-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path实现++的重载函数
89 lines (85 loc) · 1.72 KB
/
实现++的重载函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<iostream>
using namespace std;
//运算符的重载:
class People
{
//将全局函数设置成友元:
friend ostream& operator<<(ostream& out, People peo);
friend istream& operator>>(istream& in, People& peo);
private:
int age;
string name;
float score;
public:
People() {}
People(int age, string name, float score) :age(age), name(name), score(score) {}
~People() {}
//用成员函数实现+运算符的重载:
People operator+(People& p)
{
People tmp;
tmp.age = age + p.age;
tmp.name = name + p.name;
tmp.score = score + p.score;
return tmp;
}
//用成员函数实现==运算符:
bool operator==(People& p)
{
if (age == p.age && name == p.name && score == p.score)
return true;
return false;
}
//实现后置++的重载函数;
People operator++(int) //占位参数
{
People old = *this;
age++;
name = name + name;
score++;
return old;
}
People operator++()
{
age++;
name = name + name;
score++;
return *this;
}
};
//重载输出操作符:
ostream& operator<<(ostream& out, People peo)
{
out << peo.age << ' ' << peo.name << ' ' << peo.score << endl;
return out;
}
istream& operator>>(istream& in, People& peo)
{
in >> peo.age >> peo.name >> peo.score;
return in;
}
int main()
{
People John(10,"John",88);
People Danny;
#if 0
//cin >> John >> Danny;
cout << John << Danny;
//使用成员函数实现+的运算符重载:
cout << John.operator+(Danny)<<endl;
if (John == Danny)
{
cout << "相等" << endl;
}
else
{
cout << "不相等" << endl;
}
#endif
//实现++自增的重载函数:
//实现后置++
Danny = John++;
Danny = ++John;
cout << Danny << John << endl;
return 0;
}