声明Book与Ruler两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。

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
#include<iostream>
using namespace std;
class Ruler;
class Book
{
private:
int weight1;
friend void totalWeight(Book &b,Ruler &r);
public:
void init();
};

void Book::init()
{
cout<<"请输入书的重量:"<<endl;
cin>>weight1;
}

class Ruler
{
private:
int weight2;
friend void totalWeight(Book &b,Ruler &r);
public:
void init();
};

void Ruler::init()
{
cout<<"请输入尺子的重量:"<<endl;
cin>>weight2;
}

void totalWeight(Book &b,Ruler &r)
{
cout<<"二者的重量和为:"<<b.weight1+r.weight2<<endl;
}

int main()
{
Book book;
Ruler ruler;
book.init();
ruler.init();
totalWeight(book,ruler);
return 0;
}