定义一个长方形Rect类再派生出长方体类Cub.cpp 896 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include <iostream>
  2. using namespace std;
  3. // 定义长方形Rect类
  4. class Rect {
  5. public:
  6. double length;
  7. double width;
  8. double area;
  9. Rect(double l, double w) {
  10. length = l;
  11. width = w;
  12. area = length * width;
  13. }
  14. };
  15. // 派生出长方体类Cub
  16. class Cub : public Rect {
  17. public:
  18. double height;
  19. double volume;
  20. double surfaceArea;
  21. Cub(double l, double w, double h) : Rect(l,w) {
  22. height = h;
  23. volume = area * height;
  24. surfaceArea = 2 * (length*width + length*height + width*height);
  25. }
  26. };
  27. int main() {
  28. double l, w, h;
  29. cout << "输入长方体的长、宽、高:"<<endl;
  30. cin >> l >> w >> h;
  31. Cub c(l, w, h);
  32. cout << "length=" << c.length << " width=" << c.width << " height=" << c.height << endl;
  33. cout << "表面积=" << c.surfaceArea << " 体积=" << c.volume << endl;
  34. return 0;
  35. }