6-2 【CPP0025】以点类Point及平面图形类Plane为基础设计圆类Circle 分数 10 作者 C++多态编程 单位 石家庄铁道大学
以点类Point及平面图形类Plane为基类公有派生圆类Circle,main(void)函数完成对其的测试。
设计思路
类Cirlce 公有继承 两个类
在构造函数中,用setX,setY进行赋值,并对r进行赋值
Plane 中存在虚拟函数,与Circle中的函数重名
基类 表示 派生类 时有同名函数用 虚函数 可以直接调用 派生类 中的 函数,否则就是调用基类中的函数
代码
#include <iostream> using namespace std; //点类Point class Point{ private: double x; double y; public: Point(double xv=0,double yv=0);/*构造函数*/ Point(const Point &p); /*拷贝构造*/ ~Point(); /*析构函数*/ virtual void show()const; /*显示*/ void setX(double xv); /*设置X坐标*/ void setY(double yv); /*设置Y坐标*/ double getX() const; /*获取X坐标*/ double getY() const; /*获取Y坐标*/ }; Point::Point(const double xv,const double yv){/*构造函数*/ x=xv; y=yv; cout<<"Point Constructor run"<<endl; } Point::Point(const Point &p){/*拷贝构造*/ x=p.x; y=p.y; cout<<"Point CopyConstructor run"<<endl; } Point::~Point(){/*析构函数*/ cout<<"Point Destructor run"<<endl; } void Point::show() const{/*显示*/ cout<<"Point(X="<<x<<",Y="<<y<<")"; } void Point::setX(double xv){/*设置X坐标*/ x=xv; } void Point::setY(double yv){/*设置Y坐标*/ y=yv; } double Point::getX() const{/*获取X坐标*/ return x; } double Point::getY() const{/*获取Y坐标*/ return y; } class Plane{/*平面图形基类*/ public: virtual double length()const=0;/*周长*/ virtual double area()const=0; /*面积*/ }; class Circle : public Point, public Plane { const double PI = 3.14159; private: double radius; public: Circle(double x = 0.0, double y = 0.0, double r = 0.0) { setX(x); setY(y); radius = r; cout << "Circle Constructor run" << endl; } Circle(Circle &b):Point(b) { cout<<"Circle CopyConstructor run"<<endl; } ~Circle() { cout << "Circle Destructor run" << endl; } void setR(double r) { radius = r; } double getR() const { return radius; } void show() const { cout << "Circle(Point(" << "X=" << getX() << "," << "Y=" << getY() << ")," << "Radius=" << radius << ")"; } double area() const { return radius * PI * radius; } double length() const { return 2 * radius * PI; } }; void show(Point *p){/*点基类的显示函数*/ p->show(); } void length(Plane *p){/*平面图形的周长函数*/ cout<<"Length="<<p->length()<<endl; } void area(Plane &p){/*平面图形的面积函数*/ cout<<"Area="<<p.area()<<endl; } //主函数 int main(void){ double x,y,r; Circle c1,c2(c1); show(&c1); cout<<endl; area(c1); length(&c1); cin>>x>>y>>r; c2.setX(x); c2.setY(y); c2.setR(r); show(&c2); cout<<endl; area(c2); length(&c2); }
标签:const,函数,Point,double,void,多态,打卡,第十五天,yv From: https://www.cnblogs.com/youxiandechilun/p/17350662.html