定义一个抽象类,并派生出矩形类和圆形类,二者都有函数计算对象的面积,并写出main()函数进行测试。设矩形对象的长为了8,宽为5;圆形对象的半径为2.8。
3条回答 默认 最新
CSDN专家-深度学习进阶 2021-06-30 15:39关注#include<iostream> using namespace std; #define PI 3.14159 class shape{ public: virtual float getPerim() const =0; virtual void getName()const{cout<<"shape:";} shape(){} ~shape(){} }; class Rectangle:public shape{ public: Rectangle(){} ~Rectangle(){} Rectangle(float l,float w):length(l),width(w){} virtual float getPerim() const; virtual void getName()const{cout<<"Rectangle:";} private: float length,width; }; float Rectangle::getPerim() const{ return length*width; } class Circle :public shape{ public: Circle(){} Circle(float r):radius(r){} ~Circle(){} virtual float getPerim()const; virtual void getName()const{cout<<"Circle:";} private: float radius; }; float Circle::getPerim()const{ return PI*radius*radius; } int main(){ shape *sp; Circle circle(2.8); Rectangle rectangle(8,5); /*普通的访问方式,另一种是使用指针实现动态多态 circle.getName(); cout<<circle.getPerim()<<endl; rectangle.getName(); cout<<rectangle.getPerim()<<endl; */ sp=&circle; sp->getName(); cout<<sp->getPerim()<<endl; sp=&rectangle; sp->getName(); cout<<sp->getPerim()<<endl; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报