用友元函数计算Boat和Car类对象的总重量.cpp 935 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include <iostream>
  2. using namespace std;
  3. //Car类的定义与实现
  4. class Boat;
  5. class Car {
  6. private:
  7. int weight;
  8. public:
  9. Car(int w) : weight(w) {}
  10. friend int getTotalWeight(Car& aCar, Boat& aBoat);
  11. };
  12. //Boat的定义与实现
  13. class Boat {
  14. private:
  15. int weight;
  16. public:
  17. Boat(int w) : weight(w) {}
  18. friend int getTotalWeight(Car &aCar, Boat &aBoat);
  19. };
  20. //友元函数getTotalWeight()
  21. int getTotalWeight(Car& aCar, Boat& aBoat) {
  22. return aCar.weight + aBoat.weight;
  23. }
  24. int main()
  25. {
  26. int carWeight, boatWeight;
  27. cout << "卡车重量:";
  28. cin >> carWeight;
  29. cout << "轮船重量:"<<endl;
  30. cin >> boatWeight;
  31. Car myCar(carWeight);
  32. Boat myBoat(boatWeight);
  33. cout << "卡车和轮船的总重量为:" << getTotalWeight(myCar, myBoat) << endl;
  34. return 0;
  35. }