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

发布时间:2021-03-15 06:13:53

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

网友回答

#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
以上问题属网友观点,不代表本站立场,仅供参考!