定义Boat与Car两个类,两者都有私有的整型weight属性,定义两者的一个友元函数getTotalWeight(),计算二者的重量和。 用c++
时间: 2023-06-08 18:04:12 浏览: 77
语言实现如下:
```
#include<iostream>
using namespace std;
class Boat;
class Car
{
private:
int weight;
public:
friend int getTotalWeight(Car c, Boat b); // 声明友元函数
void setWeight(int w) {
weight = w;
}
};
class Boat
{
private:
int weight;
public:
friend int getTotalWeight(Car c, Boat b); // 声明友元函数
void setWeight(int w) {
weight = w;
}
};
// 实现友元函数
int getTotalWeight(Car c, Boat b) {
return c.weight + b.weight;
}
int main() {
Car myCar;
myCar.setWeight(1000);
Boat myBoat;
myBoat.setWeight(2000);
cout << "Total weight is: " << getTotalWeight(myCar, myBoat) << endl;
return 0;
}
```
输出结果为:
```
Total weight is: 3000
```