5-14
定义 Boat与Car 两个类,二者都有weight属性,定义二者的一个友元函数getTotal Weight(),计算二者的重量和。
1 #include <iostream> 2 #include <string> 3 #include <stdio.h> 4 using namespace std; 5 class Car; 6 class Boat{ 7 private: 8 int weight; 9 public: 10 friend void getTotalWeight(Boat&, Car&); 11 Boat(){weight = 0;} 12 Boat(int w){weight = w;} 13 ~Boat(){} 14 }; 15 16 class Car{ 17 private: 18 int weight; 19 public: 20 friend void getTotalWeight(Boat&, Car&); 21 Car(){weight = 0;} 22 Car(int w){weight = w;} 23 ~Car(){} 24 }; 25 26 void getTotalWeight(Boat &b, Car &c){ 27 cout<<"Totalweight:"<<b.weight+c.weight; 28 29 } 30 int main(){ 31 Boat b(100); 32 Car c(200); 33 getTotalWeight(b, c); 34 return 0; 35 36 }

浙公网安备 33010602011771号