[Task 3] WriteProgramDefines the abstract base class shape, which is derived from three Derived classes: Circle (circle), rectangle (rectangle ),
Triangle (triangle ). Use the following Mian () function to obtain the area and number of the defined ry.
Int main ()
{
Circle C1 (12.6), C2 (4.9); // create a circle Class Object C1, C2, and the parameter is the circle radius.
Rectangle r1 (4.5, 8.4), R2 (5.0, 2.5); // create rectangle class objects R1, R2. The parameter is the length and width of the rectangle.
Triangle T1 (4.5, 8.4), T2 (3.4, 2.8); // create a triangle Class Object T1, T2. The parameter is the triangle bottom edge length and height.
Shape * PT [6] ={& C1, & C2, & R1, & R2, & T1, & T2}; // defines the base class pointer array PT, 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 =" <areas <Endl; // total output area
System ("pause ");
Return 0;
}
Source program:
# Include <iostream> using namespace STD; Class shape {public: Virtual double area () const = 0 ;}; class circle: Public shape {public: Virtual double area () const {return 3.14159 * r;} circle (double r) {r = r;} PRIVATE: Double R ;}; class rectangle: Public shape {public: virtual double area () const {return long * wide;} rectangle (double L, double W) {long = L; wide = W;} PRIVATE: Double long; double Wide;}; Class triangle: Public shape {public: Virtual double area () const {return 0.5 * side * high;} triangle (double S, double H) {side = s; high = H;} PRIVATE: double side; double high ;}; int main () {circle C1 (12.6), C2 (4.9 ); // create a circle Class Object C1 and C2. The parameters are circle radius rectangle r1 (4.5, 8.4) and R2 (5.0, 2.5). // create a rectangle Class Object 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. 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 =" <areas <Endl; // total output area system ("pause"); Return 0 ;}
Running result:
Totol of allareas = 648.148
Press any key to continue...
Experience Accumulation:
Abstract accumulation is like a general. Only the combat framework is left for the soldiers to fight with a gun...