定义Boat和Car两个类,二者都有weight属性,()定义二者的一个友元函数get total weight
时间: 2024-05-05 07:23:00 浏览: 15
假设 Boat 和 Car 类的定义如下:
```cpp
class Boat {
private:
int weight;
public:
Boat(int w) : weight(w) {}
// other member functions
friend int getTotalWeight(const Boat& b, const Car& c);
};
class Car {
private:
int weight;
public:
Car(int w) : weight(w) {}
// other member functions
friend int getTotalWeight(const Boat& b, const Car& c);
};
```
可以看到,我们在类的定义中声明了一个友元函数 `getTotalWeight`,该函数的参数为一个 `Boat` 对象和一个 `Car` 对象。由于该函数是友元函数,因此可以访问 `Boat` 和 `Car` 类的私有成员变量。
下面是 `getTotalWeight` 函数的实现:
```cpp
int getTotalWeight(const Boat& b, const Car& c) {
return b.weight + c.weight;
}
```
该函数返回 `Boat` 和 `Car` 对象的重量之和。
使用示例:
```cpp
int main() {
Boat b(100);
Car c(200);
int totalWeight = getTotalWeight(b, c);
cout << "Total weight: " << totalWeight << endl; // 输出 Total weight: 300
return 0;
}
```