编写一个程序,定义Car和Boat两个类,二者都有weight属性,定义它们的一个有元函数totalweight,用友元函数计算二者的重量之和。
时间: 2024-02-17 15:05:22 浏览: 22
好的,以下是代码实现:
```c++
#include <iostream>
class Boat; // 前置声明
class Car {
private:
double weight;
public:
Car(double weight = 0) : weight(weight) {}
friend double totalweight(const Car& car, const Boat& boat);
};
class Boat {
private:
double weight;
public:
Boat(double weight = 0) : weight(weight) {}
friend double totalweight(const Car& car, const Boat& boat);
};
double totalweight(const Car& car, const Boat& boat) {
return car.weight + boat.weight;
}
int main() {
Car mycar(1000);
Boat myboat(2000);
double total = totalweight(mycar, myboat);
std::cout << "The total weight is: " << total << std::endl;
return 0;
}
```
在上述代码中,我们定义了两个类Car和Boat,它们都有weight属性。我们通过friend关键字来定义了一个友元函数totalweight,它可以访问Car和Boat的私有成员。最后,在main函数中,我们创建了一个Car对象和一个Boat对象,然后调用totalweight函数计算二者的重量之和并输出。