forked from ShiqiYu/CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
friend2.cpp
51 lines (47 loc) · 984 Bytes
/
friend2.cpp
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
#include <iostream>
using namespace std;
class Supplier;
class Sniper;
class Supplier
{
int storage;
public:
Supplier(int storage = 1000): storage(storage){}
bool provide(Sniper & sniper);
};
class Sniper
{
private:
int bullets;
public:
Sniper(int bullets = 0): bullets(bullets){}
friend bool Supplier::provide(Sniper &);
};
bool Supplier::provide(Sniper & sniper)
{
// bullets is a private member
if (sniper.bullets < 20) //no enough bullets
{
if (this->storage > 100 )
{
sniper.bullets += 100;
this->storage -= 100;
}
else if(this->storage > 0)
{
sniper.bullets += this->storage;
this->storage = 0;
}
else
return false;
}
cout << "sniper has " << sniper.bullets << " bullets now." << endl;
return true;
}
int main()
{
Sniper sniper(2);
Supplier supplier(2000);
supplier.provide(sniper);
return 0;
}