利用基类、派生类和虚函数的概念编写一个程序计算三角形、矩形和圆形的面积.

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/20 02:32:39
利用基类、派生类和虚函数的概念编写一个程序计算三角形、矩形和圆形的面积.

利用基类、派生类和虚函数的概念编写一个程序计算三角形、矩形和圆形的面积.
利用基类、派生类和虚函数的概念编写一个程序计算三角形、矩形和圆形的面积.

利用基类、派生类和虚函数的概念编写一个程序计算三角形、矩形和圆形的面积.
#include
#include
#define PI 3.14159
using namespace std;
class Shape{
public:
virtual double getArea() = 0;
protected:
double area;
};
class Triangle:public Shape{
public:
Triangle(double a,double b,double c){
this->a = a;
this->b = b;
this->c = c;
}
virtual double getArea(){
double p = (a+b+c)/2;
this->area = sqrt(p*(p-a)*(p-b)*(p-c));
return this->area;
}
private:
double a;
double b;
double c;
};
class Rectangle:public Shape{
public:
Rectangle(double width,double height){
this->width = width;
this->height = height;
}
virtual double getArea(){
this->area = this->width*this->height;
return this->area;
}
private:
double width;
double height;
};
class Circle:public Shape{
public:
Circle(double radius){
this->radius = radius;
}
virtual double getArea(){
this->area = PI*radius*radius;
return this->area;
}
private:
double radius;
};
int main(){
Shape *pTg = new Triangle(3.0,4.0,5.0);
Shape *pRtg = new Rectangle(4.0,5.0);
Shape *pCle = new Circle(5.0);
cout