用C++中面向对象的程序设计方法求不同图形面积

要求;1.掌握派生类的定义,虚函数及多态。2.定义一个图形基类。有求面积函数。3.由图形基类派生圆,矩形,三角形等。
设计思路:
类设计:
关键代码:
测试结果:
运用原理和方法:
急!求解答,

慕斯709654
浏览 780回答 2
2回答

蓝山帝景

#include <iostream>#include <math.h>#define&nbsp;PI&nbsp;3.14using namespace std;class Shape //Shape这个类里面重载了计算面积的函数{public:float Shape::GetArea(float radious)//计算圆的面积{return float (PI*radious*radious);}float Shape::GetArea(float side1, float side2, float side3)//计算三角形面积{float average=(side1+side2+side3)/2;return float (sqrt(average * (average-side1) * (average-side2) * (average-side3)));}float Shape::GetArea(float side1, float side2)//计算长方形面积{return float (side1 * side2);}};class Triangle : public Shape{public:float side1, side2 ,side3;public:Triangle(){cout<<"输入三角形三边长度:"<<endl;cin>>side1>>side2>>side3;}};class&nbsp;Circle&nbsp;: public Shape{public:float radious;public:Circle(){cout<< "输入圆的半径:"<<endl;cin>>radious;}};class Rectangle : public Shape{public:float side1, side2;public:Rectangle(){cout<<"输入长方形的长和宽:"<<endl;cin>>side1>>side2;}};int main(){int&nbsp;num;cout<<"请选择你要计算面积的图形:"<<endl<<"1.三角形 2.圆形 3.矩形"<<endl;do{cin>>num;switch(num){case 1:{Triangle* T = new Triangle;cout<<"三角形的面积为:"<<T->GetArea(T->side1, T->side2, T->side3)<<endl;delete T;break;}case 2:{Circle* C = new Circle;cout<<"圆的面积为:"<<C->GetArea(C->radious)<<endl;delete C;break;}case 3:{Rectangle* R = new Rectangle;cout<<"长方形的面积为:"<<R->GetArea(R->side1, R->side2)<<endl;delete R;break;}default:cout<<"请在1-3之间选择:";}}while (num != 1|| num != 2|| num != 3);return 0;}

UYOU

#include<iostream>using namespace std;class graph{protected:float high,wide;public:graph();graph(float h,float w){high=h;wide=w;cout<<"高为:"<<h<<"\t宽为:"<<w<<endl;} };class retangle:public graph{public:retangle(float h,float w):graph(h,w){}void area(){ cout<<"矩形的面积是:"<<high*wide<<endl;}};class triangle:public graph{public:triangle(float h,float w):graph(h,w){}void area(){ cout<<"等腰三角形的面积是:"<<high*wide/2<<endl;}};void main(){ retangle g(2,3);g.area();triangle h(2,3);h.area();}
打开App,查看更多内容
随时随地看视频慕课网APP