声明一个Shape(形状)基类,它有两个派生类:Circle(圆)和Square(正方形),

问题描述:

声明一个Shape(形状)基类,它有两个派生类:Circle(圆)和Square(正方形),
要求利用多态性的概念,分别以虚函数的形式完成对圆和正方形的周长及面积的计算.
要求:Shape类的数据成员包括中心点的坐标,Circle类和Square类初始值分别给出:圆的圆心和半径;正方形的中心和一个顶点.
1个回答 分类:综合 2014-11-29

问题解答:

我来补答
#include
#include
#define PI 3.14
class Point
{
public:
Point(){x=0;y=0;}
Point(float x,float y){this->x=x;this->y=y;}
Point(){}
float getX(){ return x;}
float getY(){ return y;}
void setX(float x){this->x=x;}
void setY(float y){this->y=y;}
private:
float x;
float y;
};
class Shape
{
public:
Shape(){this->center.setX(0);this->center.setY(0);}
Shape(Point center){
this->center.setX(center.getX());
this->center.setY(center.getY());
}
Shape(){}
virtual float getArea(){return 0;}
virtual float getCirc(){return 0;}
protected:
Point center;
};
class Circle:public Shape
{
public:
Circle(){}
Circle(Point center,float radius)
{
this->center.setX(center.getX());
this->center.setY(center.getY());
this->radius=radius;
}
Circle(){}
float getArea(){return radius*radius*PI;}
float getCirc(){return 2*PI*radius;}
private:
float radius;
};
class Square:public Shape
{
public:
Square(){}
Square(Point center,Point top){
this->center.setX(center.getX());
this->center.setY(center.getY());
this->top.setX(top.getX());
this->top.setY(top.getY());
}
Square(){}
float getArea(){
float a=top.getX()-center.getX();
float b=top.getY()-center.getY();
return 2*(a*a+b*b);
}
float getCirc(){
float a=top.getX()-center.getX();
float b=top.getY()-center.getY();
return 4*sqrt(2)*sqrt(a*a+b*b);
}
private:
Point top;
};
void main(){
Point p1(0,0),p2(4,4);
Circle c1=Circle(p1,4);
Square s1=Square(p1,p2);
Shape s=c1;
cout
 
 
展开全文阅读
剩余:2000
也许感兴趣的知识