请编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle。二者都有计算面积函数getArea(),计算周长函数getPerim()。

在此基础上,通过继承Rectangle得到一个新的类Square,然后在Square中增加一个函数int getVertexCount()const 用来捕获当前图形的顶点个数。分别用以下几种方法实现,并体会各自的优劣。
1> 使用dynamic_cast实现Shape::getVertexCount函数。
2> 使用typeid实现Shape::getVertexCount函数。
3> 将Shape::getVertexCount声明为纯虚函数,在派生类中给出具体实现

#include<iostream>
#include<cmath>
#include<iomanip>
#include<typeinfo>

using namespace std;

const double PI = 3.14159;

class Point
{
public:
	Point(double x=0.0,double y=0.0)
		:_x(x),_y(y){}

public:
	double _x, _y;
};

class Shape
{
public:
	virtual double getArea() = 0;
	virtual double getPerim() = 0;
	double getVertexCount1();

	double getVertexCount2();

	virtual double getVertexCount() = 0;

	~Shape() {}
};

class Rectangle :public Shape
{
public:
	Rectangle(const Point& p1=Point(0,0),const Point& p2=Point(0,0))
		:_p1(p1),_p2(p2)
	{}
	virtual double getArea()
	{
		return fabs((_p1._x - _p2._x)*(_p1._y - _p2._y));
	}
	virtual double getPerim()
	{
		return 2 * (fabs(_p1._x - _p2._x) + fabs(_p1._y - _p2._y));
	}
	virtual double getVertexCount()
	{
		return 4;
	}

protected:
	Point _p1;
	Point _p2;
};

class Square :public Rectangle
{
public:
	Square(Point& p1 = Point(0, 0), Point& p2 = Point(0, 0))
	{
		if (p2._x - p1._x > p2._y - p1._y)
		{
			p2._x = p1._x + (p2._y - p1._y);
		}
		else
		{
			p2._y = p1._y + (p2._x - p1._x);
		}
		_p1 = p1;
		_p2 = p2;
	}
};

class Circle :public Shape
{
public:
	Circle(const Point& pt,const double& r)
		:_ptCenter(pt),_R(r)
	{}

	virtual double getArea()
	{
		return PI*_R*_R;
	}
	virtual double getPerim()
	{
		return 2 * PI*_R;
	}
	virtual double getVertexCount()
	{
		return 0;
	}
protected:
	Point _ptCenter;
	double _R;
};

double Shape::getVertexCount1()
{
	Rectangle* pr = dynamic_cast<Rectangle*>(this);
	if (pr != NULL)
	{
		return 4;
	}

	Circle* pc = dynamic_cast<Circle*>(this);
	if (pc != NULL)
	{
		return 0;
	}
}
double Shape::getVertexCount2()
{
	const type_info& ti = typeid(*this);
	if (ti == typeid(Rectangle))
	{
		return 4;
	}
	else if (ti == typeid(Square))
	{
		return 4;
	}
	else
	{
		return 0;
	}
}

int main()
{
	Shape* arr[5];

	arr[0] = new Rectangle(Point(1, 1), Point(3, 7));
	arr[1] = new Circle(Point(1, 1), 7);
	arr[2] = new Square(Point(3, 2), Point(1, 4));
	arr[3] = new Circle(Point(5, 3), 3);
	arr[4] = new Circle(Point(5, 13), 23);

	for (int i = 0; i < 5; i++)
	{
		cout << arr[i]->getArea() << endl;
		cout << arr[i]->getPerim() << endl;
		cout << "************************" << endl;
	}

	for (int i = 0; i < 5; i++)
	{
		cout << arr[i]->getVertexCount2() << endl;
		//cout<<arr[i]->getVertexCount1() << endl;
		//cout << arr[i]->getVertexCount()<< endl;
	}

	for (int i = 0; i < 5; i++)
	{
		delete arr[i];
	}
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值