Write a program that defines the abstract base class shape, derived from it by 3 derived classes, Circle (circle), Rectangle (Rectangle), Triangle (triangle). Use the following main () function to find the area and the number of geometry defined.
int main () { Circle C1 (12.6), C2 (4.9),//Create Circle Class object C1,c2, parameters are circle radius Rectangle R1 (4.5,8.4), R2 (5.0,2.5);// Establish the Rectangle class object R1,R2, the parameters are rectangle length, width Triangle T1 (4.5,8.4), T2 (3.4,2.8),//Triangle class object T1,t2, the parameters are triangular bottom length and high Shape *pt [6]= {&c1,&c2,&r1,&r2,&t1,&t2}; Defines the base class pointer array pt, which points each element to a derived class object double areas=0.0;//areas for the total area for (int i=0; i<6; i++) { Areas=areas + Pt[i]->area (); } cout<< "Totol of all areas=" <<areas<<endl; Output total area return 0;}
/** Copyright (c) 2015, Yantai University School of Computer * All right reserved.* Shao * file: demo.cpp* finish: June 07, 2015 * version number: v1.0*/#include <iostream > #include <string>using namespace std;class shape{public:virtual Double area () = 0;}; Class Circle:public shape{private:double radius;public:circle (Double R): Radius (r) {} virtual double area () { return (3.14*radius*radius); }};class rectangle:public shape{private:double Leight; Double Height;public:rectangle (double l,double h): Leight (L), height (h) {} virtual double area () {return (l Eight*height); }};class triangle:public shape{private:double underline; Double Height;public:triangle (double u,double h): Underline (U), height (h) {} virtual double area () {return (UNDERLINE*HEIGHT*1/2); }};int Main () {Circle C1 (12.6), C2 (4.9),//Create Circle Class object C1,c2, parameter is circle radius Rectangle R1 (4.5,8.4), R2 (5.0,2.5);//Build Rectangle Class object R1,R2, the parameters are rectangle length, width Triangle T1 (4.5,8.4), T2 (3.4,2.8); Establishes the Triangle class object T1,t2, the parameter is the triangle bottom length and the height Shape *pt[6]= {&c1,&c2,&r1,&r2,&t1,&t2}; Defines the base class pointer array pt, which points each element to a derived class object double areas=0.0; Areas for the total area for (int i=0; i<6; i++) {areas=areas + Pt[i]->area (); } cout<< "Totol of all areas=" <<areas<<endl; Output total area return 0;}
Operation Result:
@ Mayuko
13th Week Item 2-pure virtual functions in the Shape class family