船和卡车的重量计算——友元函数——11-02.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <iostream>
  2. using namespace std;
  3. // Boat类定义
  4. class Boat {
  5. private:
  6. double weight; // Boat的重量,使用double以支持小数
  7. public:
  8. // Boat的构造函数
  9. Boat(double w) : weight(w) {}
  10. // Boat的析构函数
  11. ~Boat() {
  12. cout << "boat is destruction" << endl;
  13. }
  14. // 获取Boat的重量
  15. double getWeight() const {
  16. return weight;
  17. }
  18. };
  19. // Car类定义
  20. class Car {
  21. private:
  22. double weight; // Car的重量,使用double以支持小数
  23. public:
  24. // Car的构造函数
  25. Car(double w) : weight(w) {}
  26. // Car的析构函数
  27. ~Car() {
  28. cout << "car is destruction" << endl;
  29. }
  30. // 获取Car的重量
  31. double getWeight() const {
  32. return weight;
  33. }
  34. };
  35. // 友元函数,计算Boat和Car的重量和
  36. double totalweight(const Boat& b, const Car& c) {
  37. return b.getWeight() + c.getWeight();
  38. }
  39. int main() {
  40. double boatWeight, carWeight;
  41. // 从用户输入读取Boat和Car的重量
  42. cin >> boatWeight >> carWeight;
  43. // 创建Boat和Car对象
  44. Boat boat(boatWeight);
  45. Car car(carWeight);
  46. // 输出Boat和Car的重量
  47. cout << "boat's weight:" << boat.getWeight() << endl;
  48. cout << "car's weight:" << car.getWeight() << endl;
  49. // 计算并输出总重量
  50. cout.unsetf(ios::showpoint);
  51. cout << "total weight:" << totalweight(boat, car) << endl;
  52. // Boat和Car对象在main函数结束时自动析构
  53. return 0;
  54. }