(提示:此任务可以分为三个子任务分成若干步骤进行。先声明基类,再声明派生类,逐级进行,分步调试。——这种方法适用于做任何的项目)
#include <iostream> using namespace std; double const pi=3.1415926; class Point { public: Point(double x=0,double y=0); void setPoint(double , double); double getX() const {return x;} double getY() const {return y;} friend ostream & operator << (ostream &,const Point &); protected: double x,y; }; Point::Point(double a, double b) { x=a; y=b; } void Point::setPoint(double a, double b) { x=a; y=b; } ostream & operator << (ostream &output,const Point &p) { output<<"["<<p.x<<","<<p.y<<"]"<<endl; return output; } class Circle:public Point //circle是Point类的公用派生类 { public: Circle(double x=0,double y=0,double r=0); //构造函数 void setRadius(double); //设置半径值 double getRadius( ) const; //读取半径值 double area ( ) const; //计算圆面积 friend ostream &operator<< (ostream &,const Circle &);//重载运算符“<<” protected: double radius; }; //定义构造函数,对圆心坐标和半径初始化 Circle::Circle(double a,double b,double r):Point(a,b),radius(r){ } //设置半径值 void Circle::setRadius(double r) { radius=r; } //读取半径值 double Circle::getRadius( ) const { return radius; } //计算圆面积 double Circle::area( ) const { return pi*radius*radius; } //重载运算符“<<”,使之按规定的形式输出圆的信息 ostream &operator<<(ostream &output,const Circle &c) { output<<"Center=["<<c.x<<", "<<c.y<<"], r="<<c.radius<<", area="<<c.area( )<<endl; return output; } class Cylinder:public Circle { public:Cylinder(double a=0,double b=0,double r=0,double h=0); void setHigh(double); double getHigh() const; double volume() const; friend ostream &operator<< (ostream &,const Cylinder &);//重载运算符“<<” protected: double high; }; Cylinder::Cylinder(double a,double b,double r,double h):Circle(a,b,r),high(h){ } void Cylinder::setHigh(double h) { high=h; } double Cylinder::getHigh() const { return high; } double Cylinder::volume() const { return pi*radius*radius*high; } ostream &operator<<(ostream &output,const Cylinder &d) { output<<"Center=["<<d.x<<", "<<d.y<<"], r="<<d.radius<<", area="<<d.area( )<<",volume="<<d.volume( )<<endl; return output; } int main( ) { Circle c(3.5,6.4,5.2); cout<<"original circle:\nx="<<c.getX()<<", y="<<c.getY()<<", r="<<c.getRadius( ) <<", area="<<c.area( )<<endl; c.setPoint(3.5,6.4); cout<<"new circle:\n"<<c; Cylinder d(3.5,6.4,5.2,4.6); cout<<"original circle:\nx="<<d.getX()<<", y="<<d.getY()<<", r="<<d.getRadius( ) <<", area="<<d.area( )<<",volume="<<d.volume()<<endl; cout<<"new circle:\n"<<d; system("pause"); return 0; }original circle: