An abstract class is used in a sphere class.
Zookeeper
Project 3: design an abstract class CSolid, which contains two pure virtual functions to evaluate the surface area and volume. The CCube, CBall, and CCylinder classes are designed to represent cubes, sphere, and cylinder. In the main () function, define the base class pointer p (CSolid * p;), and use the p pointer to output the surface area and volume of the cube, sphere, and cylindrical objects.
Program code
# Include
Using namespace std; class Shape // Shape class {public: // calculated Shape area virtual double area () = 0 ;}; // The Shape class derives the Circle class Circle: public Shape {public: // constructor Circle (double r) {this-> r = r;} // calculate the area of the Circle virtual double area () {return 3.14 * r;} protected: double r; // radius}; // The Shape class derives the Rectangle class Rectangle: public Shape {public: // constructor Rectangle (double l, double w) {length = l; wide = w;} // calculate the area of the Rectangle virtual double area () {return length * wide ;} protected: double length; // long double wide; // width}; // Shape class derived from Triangle class Triangle: public Shape {public: Triangle (double length, double heigth) {this-> length = length; this-> height = heigth;} // calculate the area of the triangle virtual double area () {return 1/2 * length * height;} protected: double length; // bottom side length double height; // height}; void main () {Circle c1 (12.6), c2 (4.9); // create a Circle Class Object c1, c2, the parameter is the circle radius Rectangle r1 (4.5, 8.4), r2 (5.0, 2.5); // create Rectangle class objects r1, r2, the parameters are long rectangle, wide Triangle t1 (4.5, 8.4), t2 (3.4, 2.8); // create a Triangle Class Object t1, t2, the parameters are triangle bottom side length and high Shape * pt [6] ={ & c1, & c2, & r1, & r2, & t1, & t2 }; // define the base class pointer array pt so that each element points to a derived class Object double areas = 0.0; // areas is the total area for (int I = 0; I <6; I ++) {areas = areas + pt [I]-> area ();} cout <"totol of all areas =" <
Execution result