定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数getTotalWeight(),计算二者的重量和。
|
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
|
#include<iostream>
using
namespace
std;
class
Car;
class
Boat{
public
:
Boat(
int
Weight){
weight1=Weight;
}
friend
int
getTotalWeight(Boat p1,Car p2);
private
:
int
weight1;
};
class
Car{
public
:
Car(
int
Weight){
weight2=Weight;
}
friend
int
getTotalWeight(Boat p1,Car p2){
return
p1.weight1+p2.weight2;
}
private
:
int
weight2;
};
int
main(){
Boat myboat(100);
Car mycar(200);
cout<<
"The total weight is "
<<getTotalWeight(myboat,mycar)<<endl;
return
0;
}
|
本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1338333,如需转载请自行联系原作者