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

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