C++作业(第五章)5-14

题目: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;
}

运行结果

猜你喜欢

转载自blog.csdn.net/xiaorui98/article/details/81163791