一.问题描述:
定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,并求出它们的和。要求用基类指针数组。使它的每一个元素指向一个派生类的对象。PI=3.1415926
二.代码实现:
#include<iostream> using namespace std; class Shape{ public: virtual double Area()const=0; }; class Circle:public Shape{ public: Circle(double radius):r(radius){ } double r; virtual double Area()const{ return 3.1415926*r*r; } }; class Square:public Shape{ public: Square(double side):s(side){ } double s; virtual double Area()const{ return s*s; } }; class Rectangle:public Shape{ public: Rectangle(double a1,double b1):a(a1),b(b1){ } double a,b; virtual double Area()const{ return a*b; } }; class Triangle:public Shape{ public: Triangle(double width,double height):w(width),h(height){ } double w,h; virtual double Area()const{ return 0.5*w*h; } }; class Trapezoid:public Shape{ public: Trapezoid(double shangd,double xiad,double traHeight):sd(shangd),xd(xiad),th(traHeight){} double sd,xd,th; virtual double Area()const{ return (sd+xd)*th*0.5; } }; int main(){ Circle circle(12.6); Square square(3.5); Rectangle rectangle(4.5,8.4); Trapezoid trapezoid(2.0,4.5,3.2); Triangle triangle(4.5,8.4); Shape *pt[5]={&circle,&square,&rectangle,&trapezoid,&triangle}; double areas=0.0; for(int i=0;i<5;i++) { areas=areas+pt[i]->Area(); } cout<<"total of all areas = "<<areas<<endl; return 0; }
标签:const,函数,Area,double,virtual,Shape,计算,图形,public From: https://www.cnblogs.com/lzh0416/p/17389075.html