用c++怎么编?
定义一个基类Shap,包含一个求面积的纯虚函数,由Shap类派生圆类、矩形类和三角形类,定义各自的数据成员、构造函数、求面积函数和求周长函数。编写主函数,定义各类对象及基...
定义一个基类Shap,包含一个求面积的纯虚函数,由Shap类派生圆类、矩形类和三角形类,定义各自的数据成员、构造函数、求面积函数和求周长函数。编写主函数,定义各类对象及基类指针,通过基类指针调用求面积和周长函数,计算各对象的面积和周长
展开
1个回答
展开全部
#include <iostream>
#include <cmath>
using namespace std;
class Shape
{
public:
virtual double Area() = 0;
virtual double Perimeter() = 0;
};
class Circle: public Shape
{
public:
Circle(double radius = 0.0)
{
this->radius = radius;
}
virtual double Area()
{
return Circle::PI * radius * radius;
}
virtual double Perimeter()
{
return 2 * Circle::PI * radius;
}
private:
double radius;
static const double PI;
};
const double Circle::PI = 3.1415926;
class Rectangle: public Shape
{
public:
Rectangle(double length = 0.0, double width = 0.0)
{
this->length = length;
this->width = width;
}
virtual double Area()
{
return length * width;
}
virtual double Perimeter()
{
return 2 * (length + width);
}
private:
double length;
double width;
};
class Triangle: public Shape
{
public:
Triangle(double a = 0.0, double b = 0.0, double c = 0.0)
{
bool isTriangle = false;
isTriangle = (a + b > c) && (c + b > a) && (a + c > b);
if (isTriangle)
{
this->a = a;
this->b = b;
this->c = c;
}
else
{
this->a = 0.0;
this->b = 0.0;
this->c = 0.0;
}
}
virtual double Area()
{
double tmp = (a + b + c)/2;
return sqrt(tmp * (tmp - a) * (tmp - b) * (tmp - c));
}
virtual double Perimeter()
{
return (a + b + c);
}
private:
double a;
double b;
double c;
};
int main(void)
{
Shape *pSh = NULL;
Circle c(3);
Rectangle r(4, 5);
Triangle t(6, 7, 8);
pSh = &c;
cout << "Circle(3)'s Area="<<pSh->Area()<<", Perimeter="<<pSh->Perimeter()<<endl;
pSh = &r;
cout << "Rectangle(4, 5)'s Area="<<pSh->Area()<<", Perimeter="<<pSh->Perimeter()<<endl;
pSh = &t;
cout << "Triangle(6, 7, 8)'s Area="<<pSh->Area()<<", Perimeter="<<pSh->Perimeter()<<endl;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询