定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和。
时间: 2023-06-11 22:09:06 浏览: 90
以下是C++代码实现:
```cpp
#include <iostream>
using namespace std;
class Car; // 前置声明
class Boat {
private:
int weight;
public:
Boat(int w) : weight(w) {}
friend int totalWeight(Boat& b, Car& c); // 声明友元函数
};
class Car {
private:
int weight;
public:
Car(int w) : weight(w) {}
friend int totalWeight(Boat& b, Car& c); // 声明友元函数
};
int totalWeight(Boat& b, Car& c) { // 友元函数实现
return b.weight + c.weight;
}
int main() {
Boat b(100);
Car c(200);
cout << "Total weight: " << totalWeight(b, c) << endl; // 输出 Total weight: 300
return 0;
}
```
在上述代码中,我们定义了两个类 `Boat` 和 `Car`,分别有一个私有成员变量 `weight`。为了能够访问对方的私有成员变量,我们定义了一个名为 `totalWeight` 的友元函数,该函数可以访问 `Boat` 和 `Car` 类的私有成员变量。在 `main` 函数中,我们创建了一个 `Boat` 对象和一个 `Car` 对象,然后调用 `totalWeight` 函数计算二者的重量和,并输出结果。