【题解】【多态】Shape

题目描述

编写一个抽象类Shape,包含两个纯虚函数GetArea()计算面积,GetPerim()计算周长
在此基础上派生Rectangle类和circle类,给出纯虚函数的具体实现。通过继承Rectangle类,创建一个派生类Square。在主函数里创建类对象进行测试。

输入格式

输入共一行,四个浮点数,分别表示长方形的长Lenth、宽Width,圆的半径Radius,正方形的边长x

输出格式

输出共六行,分别输出长方形,圆和正方形的面积和周长,输出保留5位小数,格式如下

输入输出样例

输入 #1 复制

1.1 2.2 3.3 4.4

输出 #1 复制

Rectangle_Area=2.42000
Rectangle_Perim=6.60000
Circle_Area=34.21194
Circle_Perim=20.73451
Square_Area=19.36000
Square_Perim=17.60000

说明/提示

PI=acos(-1)

#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
double PI = acos(-1);
class Shape{
	public:
		virtual double GetArea()  = 0;
		virtual double GetPerim()  = 0;
};
class Rectangle:public Shape{
	private:
		double Length,Width;
	public:
		Rectangle(double,double);
		virtual double GetArea()  ;
		virtual double GetPerim()  ;
		void show();
		
};
class Circle:public Shape{
	private:
		double Radius;
	public:
		Circle(double);
		double GetArea()  ;
		double GetPerim()  ;
		void show();
};
class Square:public Shape{
	private:
		double x;
	public:
		Square(double);
		double GetArea() ;
		double GetPerim() ;
		void show();
};
int main(){
	double Length,Width,Radius,x;
	cin>>Length>>Width>>Radius>>x;
	Rectangle rectangle(Length,Width);
	rectangle.show();
	Circle circle(Radius);
	circle.show();
	Square square(x);
	square.show();
	return 0;
}
Rectangle::Rectangle(double Length,double Width){
	this->Length = Length;
	this->Width = Width;
}
double Rectangle::GetArea(){
	double area = Length * Width;
	return area;
}
double Rectangle::GetPerim(){
	double perim = 2 * (Length + Width);
	return perim;
}
void Rectangle::show(){
	cout<<fixed<<setprecision(5);
	cout<<"Rectangle_Area="<<GetArea()<<"\n";
	cout<<"Rectangle_Perim="<<GetPerim()<<"\n";
}
Circle::Circle(double Radius){
	this->Radius = Radius;
}
double Circle::GetArea(){
	double area = PI * Radius * Radius;
	return area;
}
double Circle::GetPerim(){
	double perim = 2 * PI * Radius;
	return perim;
}
void Circle::show(){
	cout<<fixed<<setprecision(5);
	cout<<"Circle_Area="<<GetArea()<<"\n";
	cout<<"Circle_Perim="<<GetPerim()<<"\n";
}
Square::Square(double x){
	this->x = x;
}
double Square::GetArea(){
	double area = x * x;
	return area;
}
double Square::GetPerim(){
	double perim = 4 * x;
	return perim; 
}
void Square::show(){
	cout<<fixed<<setprecision(5);
	cout<<"Square_Area="<<GetArea()<<"\n";
	cout<<"Square_Perim="<<GetPerim()<<"\n";
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值