多态

来源:互联网 发布:淘宝的匡威是正品吗 编辑:程序博客网 时间:2024/05/14 08:55

(1)通过定义形状类Shape,并派生出各类具体形状,标准模板库完成TOJ中的2034题:面积排序

(2)分析该题目中所涉及的抽象类、虚函数等概念;

(3)分析该题目特别要注意的地方。

#include <iostream>#include <string>#include <algorithm>#include <cmath>using namespace std;class Point{public:double x;double y;Point(){};Point(double _x,double _y){this -> x = _x;this -> y = _y;}};class CShape{private:string name;public:/*CShape(const string& s){this -> name = s;}*/void setname(const string& s){this -> name = s;}string getname(){return this -> name;}virtual double area() const = 0;};class CRectangle : public CShape{private:Point p1;Point p2;public:CRectangle(Point _p1,Point _p2,string s){p1 = _p1;p2 = _p2;setname(s);}virtual double area() const{return fabs((p1.x - p2.x) * (p1.y - p2.y));}};class CTriangle : public CShape{private:Point p1;Point p2;Point p3;public:CTriangle(Point _p1, Point _p2, Point _p3, string s){p1 = _p1;p2 = _p2;p3 = _p3;setname(s);}virtual double area() const{return fabs((p1.x - p2.x) * (p1.y - p3.y) - (p1.y - p2.y) * (p1.x - p3.x))/2;}};class CCircle : public CShape{private:Point p;double r;public:virtual double area() const{return acos(-1) * r * r;}CCircle(Point _p1, double _r, string s){p = _p1;r = _r;setname(s);}};bool cmp(CShape *a,CShape *b){if(fabs(a->area() - b->area()) < 1e-6){return a->getname() < b->getname();}return a->area() > b->area();}int main(){double x1,y1,x2,y2,x3,y3,r;int cnt1;int cnt2;int cnt3;int cnt = 0;cnt1 = cnt2 = cnt3 = 1;cnt = 0;CShape *pt[1000];string s;while(cin >> s){if(s == "rectangle"){char ss[10];sprintf(ss,"%d",cnt1);s += ss;cnt1++;cin >> x1 >> y1 >> x2 >> y2;Point p1(x1,y1);Point p2(x2,y2);pt[cnt] = new CRectangle(p1,p2,s);}else if(s == "triangle"){char ss[10];sprintf(ss,"%d",cnt2);s += ss;cnt2++;cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;Point p1(x1,y1);Point p2(x2,y2);Point p3(x3,y3);pt[cnt] = new CTriangle(p1,p2,p3,s);}else if(s == "circle"){char ss[10];sprintf(ss,"%d",cnt3);s += ss;cnt3++;cin >> x1 >> y1 >> r;Point p1(x1,y1);pt[cnt] = new CCircle(p1,r,s);}cnt++;}int n = cnt;sort(pt,pt+n,cmp);for(int i = 0;i < n; i++){cout << pt[i] -> getname() << " ";printf("%.3f\n",pt[i] -> area());}return 0;}


0 0
原创粉丝点击