求图形周长(三角形和矩形)并且求它们周长之和

//用shape类定义求周长函数
#include<iostream>
using namespace std;
class shape//抽象类
{
public:
	virtual float length() = 0;//求图形周长的函数
};
float total(shape *s[],int n)//求不同形状图形周长总和的函数
{
	float sum = 0.0;
	for(int i = 0;i<n;i++)
	{
		sum +=s[i]->length();
	}
	return sum;
}
class triangle:public shape//三角形
{
public:
	triangle(float a,float b,float c)
	{
		m_a = a;
		m_b = b;
		m_c = c;
	}
	~triangle(){};
	float length()
	{
		if(m_a+m_b>m_c && m_a+m_c>m_b && m_b+m_c>m_a)
			return m_a+m_b+m_c;
		else
			return -1;
	}
private:
	float m_a;
	float m_b;
	float m_c;
};
class rectangle:public shape//矩形
{
public:
	rectangle(float a,float b)
	{
		m_a = a;
		m_b = b;
	}
	~rectangle(){};
	float length()
	{
		if(m_a>0 &&m_b>0)
			return ((m_a+m_b)*2);
		else
			return -1;
	}
private:
	float m_a;
	float m_b;
};
void main()
{
	triangle t(3,4,5);
	cout<<"三角形周长 = "<<t.length()<<endl;//三角形周长
	rectangle r(3,2);
	cout<<"矩形周长 = "<<r.length()<<endl;//矩形周长
	shape *s[2];
	s[0] = new triangle(3,4,5);
	s[1] = new rectangle(3,2);
	//float sum = total(s,2);
	//cout<<"sum = "<<sum<<endl;
	cout<<"三角形和矩形周长之和 = "<<total(s,2)<<endl;//周长之和
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭