Week 2 Project 2: Define the abstract class shape, and then derive the circle (circle), rectangle (rectangle), and triangle (triangle)

Source: Internet
Author: User
/** Program Copyright and version description Section * copyright (c) 2012, Yantai University Computer college student * All rightsreserved. * Author: Li Yang * Completion Date: July 15, June 2, 2013 * version: V1.0 * input Description: none * Problem description:, define the abstract base class shape, which derives three Derived classes, circle, rectangle, and triangle ). * Program output: area of several ry and */# include <iostream> using namespace STD; Class shape {public: Virtual double area () const = 0; // define pure virtual functions}; Class circle: Public shape {public: Circle (Double R): radius (r) {} double area () const; private: double Radius ;}; double circle: Area () const {return (radius * 3.14);} class rectangle: Public shape {public: rectangle (double W, double H): width (W), height (H) {} double area () const; private: double width; double height ;}; double rectangle: Area () const {return width * height;} class triangle: Public shape {public: triangle (Double X, Double Y): WID (x), hei (y) {} double area () const; private: Double WID; double Hei;}; double triangle: Area () const {return 0.5 * WID * Hei;} int main () {circle C1 (12.6 ), c2 (4.9); // create a circle Class Object C1 and C2. The parameters are round radius rectangle r1 (4.5, 8.4), R2 (5.0, 2.5 ); // create rectangle class objects R1 and R2. The parameters are long rectangle, wide triangle T1 (4.5, 8.4), and T2 (3.4, 2.8). // create a triangle Class Object T1, t2, the parameter is 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 =" <areas <Endl; // return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.