c++ 第六章第五题

#include <iostream>
#include<string>
using namespace std;

class Shape{
public:
	virtual float area() const=0;
	virtual string getName() const=0;
};

//三角形
class Triangle:public Shape
{
	private:
		double height;
		double width;

	public:
		virtual float area() const{
			return (height*width)/2;
		}
		Triangle(double h,double w){
			height=h;
			width=w;
		}
		virtual string getName() const{
		return "三角形";
		}
};
//圆形
class Circle:public Shape{
	private:
		double r;
	public:
		virtual float area() const{
			return 3.14*r*r;
		}
		Circle(double R){
			r=R;
		}
		virtual string getName() const{
		return "圆形";
		}
};

//矩形
class Rectangle: public Shape{
	private:
		double width;
		double height;
	public:
		virtual float area() const{
		return width*height;
		}
		Rectangle(double w,double h){
		width=w;
		height=h;
		}
		virtual string getName() const{
		return "矩形";
		}
};
//正方形
class Square: public Shape{
	private:
		double width;
	public:
		virtual float area() const{
		return width*width;
		}
		Square(double w){
		width=w;
		}
		virtual string getName() const{
		return "正方形";
		}
};
//梯形
class Trapezoid: public Shape{
	private:
		double width1;
		double width2;
		double height;
	public:
		virtual float area() const{
		return (width1+width2)*height/2;
		}
		Trapezoid(double w1,double w2,double h){
		width1=w1;
		width2=w2;
		height=h;
		}
		virtual string getName() const{
		return "梯形";
		}
};

int main(){
	Triangle t(33.0,2.5);
	Circle c(1.0);
	Rectangle r(4.2,5.2);
	Square s(23.0);
	Trapezoid tr(12.3,23.2,11.3);
	Shape* shape[5]={&t,&c,&r,&s,&tr};
	for(int i=0;i<5;i++){
		cout<<shape[i]->getName()<<"面积:"<<shape[i]->area()<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值