- #ifndef CSOLID_H_INCLUDED
- #define CSOLID_H_INCLUDED
- class CSolid
- {
- public:
- virtual double surfaceArea() = 0;
- virtual double volume() = 0;
- };
- class CCube:public CSolid
- {
- public:
- CCube(double l, double w, double h):length(l),width(w),height(h){}
- double surfaceArea();
- double volume();
- private:
- double length;
- double width;
- double height;
- };
- class CBall:public CSolid
- {
- public:
- CBall(double r):radius(r){}
- double surfaceArea();
- double volume();
- private:
- static constexpr double PI = 3.1415926;
- double radius;
- };
- class CCylinder:public CSolid
- {
- public:
- CCylinder(double r, double h):radius(r),height(h){}
- double surfaceArea();
- double volume();
- private:
- static constexpr double PI = 3.1415926;
- double radius;
- double height;
- };
- #endif // CSOLID_H_INCLUDED
- #include "CSolid.h"
- double CCube::surfaceArea()
- {
- return (length*width + length*height + width*height)*2;
- }
- double CCube::volume()
- {
- return length * height * width;
- }
- double CBall::surfaceArea()
- {
- return 4 * PI * radius * radius;
- }
- double CBall::volume()
- {
- return (4*PI*radius*radius*radius) / 3;
- }
- double CCylinder::surfaceArea()
- {
- return 2*PI*radius*height + PI*radius*radius*2;
- }
- double CCylinder::volume()
- {
- return PI*radius*radius*height;
- }
main.cpp
- #include <iostream>
- #include "CSolid.h"
- using namespace std;
- int main()
- {
- CSolid *p = nullptr;
- CCube cube(1,2,3);
- p = &cube;
- cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;
- CBall ball(2);
- p = &ball;
- cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;
- CCylinder cylinder(2,2);
- p = &cylinder;
- cout << " 表面积:" << p->surfaceArea() << " 体积:" << p->volume() << endl;
- return 0;
- }