问题及代码:
/*copyright 计算机与控制工程学院
完成日期:2016年5月6日
作者:马艳艳
问题描述:再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高),,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main函数完成测试。
输出描述:圆柱体积面积;
*/
#include <iostream>
using namespace std;
const float PI=3.1415926;
class Point
{
public:
Point(double x=0,double y=0); //构造函数
void setPoint(double,double); //设置坐标值
double getX( ) const {return x;} //x坐标
double getY( ) const {return y;} //y坐标
void show();
//受保护成员
double x,y;
};
Point::Point(double a,double b)
{
x=a;
y=b;
}
//设置x和y的坐标值
void Point::setPoint(double a,double b)
{
x=a;
y=b;
}
void Point::show()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
class Circle:public Point
{
protected:
double r;
public:
Circle (double x=0,double y=0,double r=0);
void setR(double);
double area()const;
void show();
};
Circle ::Circle(double a,double b,double r):Point (a,b),r(r){}//设置圆的构造函数
void Circle::setR(double r)
{
this->r=r;
}
double Circle::area()const
{
return PI*r*r;//求圆的面积
}
void Circle ::show()
{
cout<<"圆心坐标为:"<<endl;
cout<<"("<<x<<","<<y<<")"<<endl;
cout<<"半径为:"<<endl;
cout<<r<<endl;
}
class Cylineder :public Circle
{
public:
Cylineder(double x=0,double y=0,double r=0,double h=0);//构造圆柱体的构造函数
void setH(double);//设置圆柱的高
double getH()const;//读取高
double area()const;//求圆柱的面积
double volume()const;//求圆柱的体积
void show();//显示圆柱的信息
protected:
double h;
};
Cylineder::Cylineder(double a,double b,double r,double h):Circle(a,b,r),h(h){}
void Cylineder::setH(double h){this->h=h;}
double Cylineder::getH()const{ return h;}
double Cylineder::area()const//求圆柱体表面积
{
return 2*Circle::area( )+2*PI*r*h;
}
double Cylineder::volume()const
{
return Circle::area()*h;
}
void Cylineder::show()
{
cout<<"Center=("<<x<<","<<y<<"), r="<<r<<", h="<<h
<<"\narea="<<area()<<", volume="<<volume()<<endl;
}
int main( )
{
Cylineder cy1(3.5,6.4,5.2,10);
cy1.show();
cy1.setH(15);
cy1.setR(7.5);
cy1.setPoint(5,5);
cy1.show();
return 0;
}
运行结果:
知识点总结:
我感觉我在写输出圆柱体积那里出错,因为输出时在point那里用的是x,y;但我用的是a,b,所以应该是要保持一致性。因为Circle继承point,cylineder继承Circle。