任务描述:
定义抽象类Shape,在此基础上派生出圆类Circle、正方形类Square、三角形类Triangle,3个派生类都有构造函数,输入和显示信息函数Input()、Show(),计算面积的函数Area(),计算周长的函数Perim()。完成以上类的编写,在主函数中动态创建3类对象,通过基类的指针指向派生类对象,并调用派生类对象相应函数。
源代码:
#include <iostream> #include <cmath> using namespace std; const double PI=3.14159; //定义抽象基类Shape class Shape { public: virtual double Area() const =0; virtual double Perim() const =0; virtual void Input() =0; virtual void Show()=0; virtual void ShowName()=0; }; //定义Circle(圆形)类 class Circle:public Shape { public: Circle(double r):radius(r){} void Input(){ cin>>radius; } void ShowName(){ cout<<"*******圆形********"<<endl; } double Perim() const { return 2*PI*radius; } double Area() const { return radius*radius*PI; } void Show(){ cout<<"radius="<<radius<<endl; cout<<"Area="<<Area()<<endl; cout<<"Perim="<<Perim()<<endl<<endl; } protected: double radius; }; //定义Square(正方形)类 class Square:public Shape {public: Square(double s):side(s){} void Input(){ cin>>side; } void ShowName(){ cout<<"*******正方形********"<<endl; } double Perim() const { return 4*side; } double Area() const { return side*side; } void Show(){ cout<<"side="<<side<<endl; cout<<"Area="<<Area()<<endl; cout<<"Perim="<<Perim()<<endl<<endl; } protected: double side; }; //定义Triangle(三角形)类 class Triangle:public Shape { public: Triangle(double aa,double bb,double cc):a(aa),b(bb),c(cc){} void Input(){ cin>>a>>b>>c; } void ShowName(){ cout<<"*******三角形********"<<endl; } double Perim() const { return a+b+c; } double Area() const { double per; per=(a+b+c)/2; return sqrt(per*(per-a)*(per-b)*(per-c)); } void Show(){ cout<<"a,b,c="<<a<<" "<<b<<" "<<c<<endl; cout<<"Area="<<Area()<<endl; cout<<"Perim="<<Perim()<<endl<<endl; } protected: double a,b,c; }; int main() { Shape* sh[3]; Circle c(0); sh[0]=&c; sh[0]->Input(); sh[0]->ShowName(); sh[0]->Show(); sh[0]->Area(); sh[0]->Perim(); Square s(0); sh[1]=&s; sh[1]->Input(); sh[1]->ShowName(); sh[1]->Show(); sh[1]->Area(); sh[1]->Perim(); Triangle t(0,0,0); sh[2]=&t; sh[2]->Input(); sh[2]->ShowName(); sh[2]->Show(); sh[2]->Area(); sh[2]->Perim(); cout<<"Total of all Areas="<<c.Area()+s.Area()+t.Area()<<endl; cout<<"Total of all Perims="<<c.Perim()+s.Perim()+t.Perim()<<endl; return 0; }
输入:
12.7 3.9 5 6 7
测试结果:
*******圆形******** radius=12.7 Area=506.707 Perim=79.7964 *******正方形******** side=3.9 Area=15.21 Perim=15.6 *******三角形******** a,b,c=5 6 7 Area=14.6969 Perim=18 Total of all Areas=536.614 Total of all Perims=113.396