/*
*Copyright(c) 2016,烟台大学计算机学院
*作 者:刘金石
*完成日期:2016年5月4日
*问题描述:点-圆-圆柱继承设计
*/
//(1)先建立一个Point(点)类,包含数据成员x,y(坐标点),实现需要的成员函数,并设计main函数完成测试;
#include<iostream>
using namespace std;
class Point
{
double x,y;
public:
Point(){}
Point(double xx,double yy):x(xx),y(yy){}
void setPoint(double xx,double yy)
{
x=xx;
y=yy;
}
void showPoint()
{
cout<<x<<" "<<y<<endl;
}
void getX()
{
return x;
}
void getY()
{
return y;
}
};
int main()
{
Point point1;
Point point2(4,5);
point1.setPoint(2,3);
point1.showPoint();
point2.showPoint();
return 0;
}
运行结果:
(2)以Point为基类,派生出一个Circle(圆)类,增加数据成员r(半径),以及求面积的成员函数area,实现其他需要的成员函数,设计main函数完成测试;
#include<iostream>
using namespace std;
class Point
{
double x,y;
public:
Point(){}
Point(double xx,double yy):x(xx),y(yy){}
void setPoint(double xx,double yy)
{
x=xx;
y=yy;
}
void showPoint()
{
cout<<x<<" "<<y<<endl;
}
double getX()
{
return x;
}
double getY()
{
return y;
}
};
class Circle:public Point
{
double r;
public:
Circle(double xx,double yy,double rr):Point(xx,yy),r(rr){}//继承类的构造函数
Circle(){}
double area();
double getR()//得到半径的值
{
return r;
}
void show_R_area()
{
cout<<"半径:"<<r<<" "<<"面积:"<<area()<<endl;
}
void setR(double rr)
{
r=rr;
}
};
double Circle::area()
{
return 3.1415926*r*r;
}
int main()
{
Circle C1(2,3,4);
Circle C2;
C2.setPoint(1,2);
C2.setR(3);
C1.show_R_area();
C2.show_R_area();
return 0;
}
运行结果:
(3)再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高)
,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main函数完成测试。
#include<iostream>
using namespace std;
class Point
{
double x,y;
public:
Point(){}
Point(double xx,double yy):x(xx),y(yy){}
void setPoint(double xx,double yy)
{
x=xx;
y=yy;
}
void showPoint()
{
cout<<x<<" "<<y<<endl;
}
double getX()
{
return x;
}
double getY()
{
return y;
}
};
class Circle:public Point
{
double r;
public:
Circle(double xx,double yy,double rr):Point(xx,yy),r(rr){}//继承类的构造函数
Circle(){}
double area();
double getR()//得到半径的值
{
return r;
}
void show_R_area()
{
cout<<"半径:"<<r<<" "<<"面积:"<<area()<<endl;
}
void setR(double rr)
{
r=rr;
}
};
double Circle::area()
{
return 3.1415926*r*r;
}
class Cylinder:public Circle
{
double h;
public:
Cylinder(){}
Cylinder(double xx,double yy,double rr,double hh):Circle(xx,yy,rr),h(hh){}
double area();
double getH()
{
return h;
}
double volume();
void show()
{
cout<<"半径:"<<getR()<<" "<<"高:"<<h<<" "<<"面积:"<<area()<<"体积:"<<volume()<<endl;
}
void setH(double hh)
{
h=hh;
}
};
double Cylinder::area()
{
double S,L;
L=3.1415926*getR()*2;//底面周长
S=3.1415926*getR()*getR()*2;//上下底面积
return L*getH()+S;
}
double Cylinder::volume()
{
return 3.1415926*getR()*getR()*getH();
}
main()
{
Cylinder Cy1(1,2,3,4);
Cylinder Cy2;
Cy2.setPoint(1,2);
Cy2.setR(3);
Cy2.setH(4);
Cy1.show();
Cy2.show();
return 0;
}
运行结果: