写一个C++编程,定义Boat与C a r两个类,二者都有weight属性,定义二者的一个友元函数getTotalWeight(),计算二者的重量和。
时间: 2024-10-28 18:07:05 浏览: 11
Exe7_0友元_C++友元函数编程(两种有友元方式)_cloudzfv_
当然可以。在C++中,我们可以创建一个友元函数来访问私有成员,这里是一个简单的示例,包含`Boat`和`Car`两个类,它们都有`weight`属性,并有一个友元函数`getTotalWeight`来计算它们总重量:
```cpp
#include <iostream>
class Boat {
private:
double weight; // 船的重量
public:
Boat(double boat_weight) : weight(boat_weight) {}
double getWeight() const { return weight; }
friend double getTotalWeight(const Boat& boat, const Car& car); // 宣告为友元函数
};
class Car {
private:
double weight; // 汽车的重量
public:
Car(double car_weight) : weight(car_weight) {}
double getWeight() const { return weight; }
};
// 友元函数实现
double getTotalWeight(const Boat& boat, const Car& car) {
return boat.getWeight() + car.getWeight(); // 计算并返回两者的总重量
}
int main() {
Boat myBoat(500.0);
Car myCar(1200.0);
double total = getTotalWeight(myBoat, myCar);
std::cout << "The total weight of the boat and car is: " << total << " kg.\n";
return 0;
}
```
在这个例子中,`getTotalWeight`函数虽然不在`Boat`或`Car`类内部,但可以直接访问它们的`weight`属性,因为它是这两个类的友元。
阅读全文