这是个由Point为基类派生出 class Circle ,class Cylinder输出点的坐标,以该点为圆心的圆的面积,和以该圆为底高为height的圆柱体的表面积和体积;
#include<iostream>
using namespace std;
class Point//define class Point;
{public:
Point(float x=0,float y=0);
void setPoint(float a,float b);
float getX() const{return x;};
float getY() const{return y;};
friend ostream & operator <<(ostream &,const Point &);
protected:
float x,y;
};
//define class Point member function;
Point::Point(float a,float b):x(a),y(b){}
void Point::setPoint(float a,float b):x(a),y(b){}//为什么不能这么写?而只能写成 void Point::setPoint(float a,float b){x=a;y=b;}是不是跟x,y是protected有关?同样还有下面几个函数也一样的问题;
ostream & operator <<(ostream &putout,const Point &p)
{ putout<<"["<<p.x<<","<<p.y<<"]"<<endl;
return putout;
}
class Circle:public Point//define class Circle;
{public:
Circle(float x=0,float y=0,float r=0);
void setRadius(float);
float getRadius() const{return radius;}
float area() const;
friend ostream & operator <<(ostream &,const Circle &);
protected:
float radius;
};
//define class member function;
Circle::Circle(float x,float y,float r):Point(x,y),radius(r){}
void Circle::setRadius(float r)
{radius=r;}//只能这样写么?不能用参数初始化表么? 同上函数:void Point::setPoint(float a,float b);
float Circle::area() const {return 3.14159*radius*radius;}
ostream & operator <<(ostream &putout,Circle &c)
{ putout<<"Center:["<<c.getX()<<","<<c.getY()<<"],r="<<c.getRadius()<<"area="<<c.area()<<endl;
return putout;
}
//define class Cylinder;
class Cylinder:public Circle
{public:
Cylinder(float x=0,float y=0,float r=0,float h=0);
void setHeight(float);
float getHeight() const{return height;}
float area() const{return 2*Circle::area()+2*3.14159*radius*height;}
float volume() const{return Circle::area()*height;}
friend ostream & operator <<(ostream &,Cylinder &);
protected:
float height;
};
//define member function ;
Cylinder::Cylinder(float a,float b,float r,float h):Circle(a,b,r),height(h){}
void Cylinder::setHeight(float h)
{h=height;}//只能这样写么?不能用参数初始化表么? 同上函数:void Point::setPoint(float a,float b);
ostream & operator <<(ostream & putout,Cylinder & cy)
{putout<<"Center=["<<cy.getX()<<","<<cy.getY()<<"],r="<<cy.getRadius()<<",h="<<cy.height<<",area="<<cy.area()<<",volume="<<cy.volume()<<endl;
return putout;
}
int main()
{Cylinder cy1(3.5,6.4,5.2,10);
cout<<"\noriginal cylinder:\nx="<<cy1.getX()<<",y="<<cy1.getY()<<",r="<<cy1.getRadius()<<",h="<<cy1.getHeight()<<",area=";
cout<<cy1.area()<<",volume="<<cy1.volume()<<endl;
cy1.setHeight(15);
cy1.setRadius(7.5);
cy1.setPoint(5,5);
cout<<"\nnew cylinder\n"<<cy1;
Point &pRef=cy1;
cout<<"\npRef as a point:\n"<<pRef;
Circle &cRef=cy1;
cout<<"\ncRef as a circle:\n"<<cRef;
system("pause");
return 0;
}
[此贴子已经被作者于2007-3-15 23:30:31编辑过]