#include <iostream>
using namespace std;
class Car; // 前向声明Car类,以便Boat类中声明友元函数
class Boat {
private:
int weight;
public:
Boat(int w) : weight(w) {}
friend int getTotalWeight(Boat b, Car c); // 声明友元函数
};
class Car {
private:
int weight;
public:
Car(int w) : weight(w) {}
friend int getTotalWeight(Boat b, Car c); // 声明友元函数
};
// 友元函数的定义
int getTotalWeight(Boat b, Car c) {
return b.weight + c.weight;
}
int main() {
int boatWeight, carWeight;
cout << "Input boat weight:";
cin >> boatWeight;
cout << "Input car weight:";
cin >> carWeight;
Boat boat(boatWeight);
Car car(carWeight);
int totalWeight = getTotalWeight(boat, car);
cout << "Total weight:" << totalWeight << endl;
return 0;
}
【输入形式】
参考的输入(数字前为提示文字):
Input boat weight:3
Input car weight:5
【输出形式】
参考的输出:
Total weight:8