定义一boat与一car两个类,二者具有weight属性,定义二者的一个友元函数,计算二者重量之和
时间: 2023-12-30 10:06:51 浏览: 25
好的,根据您的要求,我来为您编写一个C++的代码实现:
```c++
class Car; // 先声明Car类,因为在Boat类中需要用到
class Boat {
private:
double weight;
public:
Boat(double w = 0) : weight(w) {}
friend double getTotalWeight(const Boat& b, const Car& c);
};
class Car {
private:
double weight;
public:
Car(double w = 0) : weight(w) {}
friend double getTotalWeight(const Boat& b, const Car& c);
};
double getTotalWeight(const Boat& b, const Car& c) {
return b.weight + c.weight;
}
int main() {
Boat b(1000);
Car c(2000);
double totalWeight = getTotalWeight(b, c);
std::cout << "Total weight: " << totalWeight << std::endl;
return 0;
}
```
这里定义了Boat和Car两个类,二者都具有weight属性,并且定义了一个友元函数getTotalWeight,用于计算二者重量之和。在Boat和Car类中都声明了getTotalWeight为友元函数。在主函数中创建了一个Boat对象和一个Car对象,并调用getTotalWeight函数计算二者重量之和。输出结果为:
```
Total weight: 3000
```
希望这个代码对您有所帮助!