在此基础上,通过继承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;
}