用C++编写一个程序声明boat与car两个类,两者都有weight属性,定义二者的一个友元函数totalweight(),计算二者的重量和。类的信息按需要自行定义。 【输入形式】在主程序中输入一个boat对象以及一个car对象的重量 【输出形式】输出两个对象的重量和 【样例输入1】4 5 【样例输出1】9
时间: 2023-12-02 22:06:28 浏览: 20
好的,这是您的问题:
根据您的要求,我会帮您编写一个程序,声明 boat 与 car 两个类,两者都有 weight 属性,定义二者的一个友元函数 totalweight(),计算二者的重量和。类的信息按需要自行定义。以下是代码实现:
```c++
#include <iostream>
using namespace std;
class car; // 前向声明
class boat {
public:
boat(int w = 0) { weight = w; }
friend int totalweight(boat b, car c);
private:
int weight;
};
class car {
public:
car(int w = 0) { weight = w; }
friend int totalweight(boat b, car c);
private:
int weight;
};
int totalweight(boat b, car c) {
return b.weight + c.weight;
}
int main() {
int weight1, weight2;
cout << "Please input the weight of the boat:\n";
cin >> weight1;
boat b(weight1);
cout << "Please input the weight of the car:\n";
cin >> weight2;
car c(weight2);
cout << "The total weight is: " << totalweight(b, c) << endl;
return 0;
}
```
以上是完整的 C++ 代码实现,您可以直接复制到本地运行查看效果。
当您运行程序后,会先要求您分别输入 boat 对象与 car 对象的重量。程序会根据您的输入,创建对应的 boat 对象与 car 对象,并调用 totalweight() 函数计算二者的重量和,最后输出结果。
比如,当您分别输入 boat 对象与 car 对象的重量为 4 和 5 时,程序会输出二者的重量和为 9。