【C/C++】多态-抽象基类Shape派生3个类

题目描述:
请实现一个抽象类Shape及接口方法(double area();double perimeter())和三个派生类Rect、Triangle、Circle,通过构造三种派生类的对象的方式来计算给出的矩形、三角形和圆形的面积area和周长perimeter。

输入描述:

有多行输入,第一行为几何形状的数目n,其余n行,每行代表一个形状

其中每行第一个字符串为几何形状字符串,矩形为Rect,三角形为Triangle,圆形为Circle(请注意大小写)。

其余为相应形状的几何数据数字,之间用空格分隔(每个点用x,y两个坐标表示,x坐标在前,y坐标在后),如

Rect x1 y1 x2 y2

Circle x y r

Triangle x1 y1 x2y2 x3 y3

输出描述:

有多行结果,每行为对应几何形状的面积和周长(保留到小数点后5位),两个数字之间用一个空格分隔。

示例1:

输入:

3
Rect 0 0 2 4
Circle 0 0 3
Triangle 0 0 2 2 2 0

输出:

8.00000 12.00000
28.27433 18.84956
2.00000 6.82843

#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
#define pi 3.1415926
using namespace std;
class Shape//形状
{
protected:
	double perimeter;
	double area;
};
class Rect :public Shape//矩形
{
protected:
	int x1, y1, x2, y2;
public:
	Rect(int x1,int y1,int x2,int y2)
	{
		this->x1 = x1;
		this->y1 = y1;
		this->x2 = x2;
		this->y2 = y2;
	}
	double Get_Perimeter()
	{
		return ((y2 - y1) + (x2 - x1)) * 2;
	}
	double Get_Area()
	{
		return (y2 - y1)* (x2 - x1);
	}
};
class Triangle :public Shape//三角形
{
protected:
	int x1, y1, x2, y2, x3, y3;
	double a, b, c;
public:
	Triangle(int x1, int y1, int x2, int y2, int x3, int y3)
	{
		this->x1 = x1;
		this->y1 = y1;
		this->x2 = x2;
		this->y2 = y2;
		this->x3 = x3;
		this->y3 = y3;
	}
	void get_abc()
	{
		a = sqrt((y2 - y1)*(y2 - y1) + (x2 - x1)*(x2 - x1));
		b = sqrt((y3 - y1)*(y3 - y1) + (x3 - x1)*(x3 - x1));
		c = sqrt((y2 - y3)*(y2 - y3) + (x2 - x3)*(x2 - x3));
	}
	double Get_Perimeter()
	{
		return a + b + c;
	}
	double Get_Area()
	{
		double p = (a + b + c)*1.0 / 2;
		return sqrt(p*(p - a)*(p - b)*(p - c));
	}
};
class Circle :public Shape//圆
{
protected:
	int x, y, r;
public:
	Circle(int x, int y, int r)
	{
		this->x = x;
		this->y = y;
		this->r = r;
	}
	double Get_Perimeter()
	{
		return 2 * pi*r;
	}
	double Get_Area()
	{
		return pi*r*r;
	}
};
int main()
{
	int n;
	cin >> n;
	while (n--)
	{
		string s;
		cin >> s;
		if (s == "Rect")//矩形
		{
			int x1, y1, length, width;
			cin >> x1 >> y1 >> length >> width;
			Rect rect(x1, y1, length, width);
			printf("%.5lf %.5lf\n", rect.Get_Area(), rect.Get_Perimeter());

		}
		else if (s == "Triangle")//三角形
		{
			int x1, y1, x2, y2, x3, y3;
			cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
			Triangle triangle(x1, y1, x2, y2, x3, y3);
			triangle.get_abc();
			printf("%.5lf %.5lf\n", triangle.Get_Area(), triangle.Get_Perimeter());
		}
		else if (s == "Circle")//圆
		{
			int x, y, r;
			cin >> x >> y >> r;
			Circle circle(x, y, r);
			printf("%.5lf %.5lf\n", circle.Get_Area(), circle.Get_Perimeter());
		}
	}
	return 0;
}

思路:定义一个基类Shape,包含两个成员周长和面积,便于子类继承。

注:子类继承父类的所有成员,不包括构造析构函数,子类中写自己的构造函数和析构函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值