欢迎来到天天文库
浏览记录
ID:39130848
大小:74.51 KB
页数:13页
时间:2019-06-25
《多态性和虚函数》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、ProblemA:C++习题抽象基类Description编写一个程序,声明抽象基类Shape,由它派生出3个派生类:Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别输出以上三者的面积(结果保留两位小数),3个图形的数据在定义对象时给定。Input圆的半径矩形的边长三角形的底与高Output圆的面积矩形的面积三角形的面积SampleInput12.64.58.44.58.4SampleOutputareaofcircle=498.76ar
2、eaofrectangle=37.80areaoftriangle=18.90#include#includeusingnamespacestd;classShape{public:virtualdoublearea()const=0;};classCircle:publicShape{public:Circle(doubler):radius(r){}virtualdoublearea()const{return3.14159*radius*radius;};
3、protected:doubleradius;};classRectangle:publicShape{public:Rectangle(doublew,doubleh):width(w),height(h){}virtualdoublearea()const{returnwidth*height;}protected:doublewidth,height;};classTriangle:publicShape{public:Triangle(doublew,doubleh):width(w),he
4、ight(h){}virtualdoublearea()const{return0.5*width*height;}protected:doublewidth,height;};voidprintArea(constShape&s){cout<>r;Circlecircle(r);cout<<"areaofcircle=";printArea(circ
5、le);cin>>a>>b;Rectanglerectangle(a,b);cout<<"areaofrectangle=";printArea(rectangle);cin>>w>>h;Triangletriangle(w,h);cout<<"areaoftriangle=";printArea(triangle);return0;}ProblemB:C++习题虚函数-计算图形面积Description编写一个程序,定义抽象基类Shape,由它派生出5个派生类:Circle(圆形)、Square(
6、正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形)。用虚函数分别计算几种图形面积,并求它们之和。要求用基类指针数组,使它每一个元素指向一个派生类对象。 Input圆的半径正方形的边长矩形的边长梯形的上底和下底,高三角形的底与高Output所有图形面积之和(结果保留两位小数)SampleInput12.63.54.58.42.04.53.24.58.4SampleOutputtotalofallareas=574.11#include#in
7、cludeusingnamespacestd;classShape{public:virtualdoublearea()const=0;};classCircle:publicShape{public:Circle(doubler):radius(r){}virtualdoublearea()const{return3.14159*radius*radius;};protected:doubleradius;};classSquare:publicShape{public:Squa
8、re(doubles):side(s){}virtualdoublearea()const{returnside*side;}protected:doubleside;};classRectangle:publicShape{public:Rectangle(doublew,doubleh):width(w),height(h){}virtualdoublearea()const{returnwidth*height;}protected:doublewidth,he
此文档下载收益归作者所有