定义Boat与Car两个类,两者都有私有的整型weight属性,要求定义一个getTotalWeight()函数,计算二者对象的重量和。 要求按以下方式分别实现: 1、定义getTotalWeight()为普通函数 2、定义getTotalWeight()为Boat类或者Car类的成员函数
时间: 2023-06-01 15:01:44 浏览: 70
1. 定义getTotalWeight()为普通函数:
```c++
class Boat {
private:
int weight;
public:
Boat(int w) { weight = w; }
friend int getTotalWeight(Boat b, Car c);
};
class Car {
private:
int weight;
public:
Car(int w) { weight = w; }
friend int getTotalWeight(Boat b, Car c);
};
int getTotalWeight(Boat b, Car c) {
return b.weight + c.weight;
}
```
2. 定义getTotalWeight()为Boat类或者Car类的成员函数:
```c++
class Boat {
private:
int weight;
public:
Boat(int w) { weight = w; }
int getTotalWeight(Car c) {
return weight + c.weight;
}
};
class Car {
private:
int weight;
public:
Car(int w) { weight = w; }
int getTotalWeight(Boat b) {
return weight + b.weight;
}
};
```
使用方法:
```c++
Boat b(100);
Car c(200);
int totalWeight = getTotalWeight(b, c); // 普通函数方式
int totalWeight = b.getTotalWeight(c); // Boat类成员函数方式
int totalWeight = c.getTotalWeight(b); // Car类成员函数方式
```