题目:5-14 定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。
#include <iostream>
using namespace std;
class Boat;
class Car
{
public:
Car(int j){weight = j;}
friend int totalWeight(Car &aCar,Boat &aBoat);
private:
int weight;
};
class Boat
{
public:
Boat(int j){weight = j;}
friend int totalWeight(Car &aCar,Boat &aBoat);
private:
int weight;
};
int totalWeight(Car &aCar, Boat &aBoat)
{
return aCar.weight + aBoat.weight;
}
int main()
{
Car c1(1);
Boat b1(2);
cout << totalWeight(c1, b1) << endl;
return 0;
}
运行结果