从点类派生圆类,再由圆类派生圆柱类

2021年1月15日 253点热度 0条评论 来源: thistle2012

从点类派生圆类,再由圆类派生圆柱类

#include <iostream>
#include <string.h>
using namespace std;
const double pi=3.14;
class Point
{
private:
    int x, y; //点的x和y坐标
public:
    Point( int = 0, int = 0 ); // 构造函数
    void SetPoint( int, int ); // 设置坐标
    int GetX() { return x; } // 取x坐标
    int GetY() { return y; } // 取y坐标
    void Print(); //输出点的坐标
};
Point::Point( int a, int b ) { SetPoint( a, b ); }
void Point::SetPoint( int a, int b ) { x = a; y = b; }
void Point::Print() { cout << "[" << x << "," << y << "]";}
//从点类派生出圆类
class Circle:public Point{
private:
    double radius;
public:
    Circle(int x = 0, int y = 0 , double r = 0.0); //对数据成员赋值,并使用SetRadius和基类的Point
    void SetRadius( double ); //设置半径
    double GetRadius(); //取半径
    double Area(); //计算面积
    void Print(); //输出圆心坐标和半径,并使用基类的Print
};
Circle::Circle(int x,int y,double r):Point(x,y)
{
    SetRadius(r);
}
void Circle::SetRadius(double r)
{
    radius=(r>=0?r:0);
}
double Circle::GetRadius()
{
    return radius;
}
double Circle::Area()
{
    return pi*radius*radius;
}
void Circle::Print()
{
    cout<<"Center=";
    Point::Print();
    cout<<";Radius="<<radius<<endl;
}
//从圆类派生出圆柱类
class Cylinder:public Circle{
private:
    double high;
public:
    Cylinder(int x,int y,double r,double h);
    void Set_data(int x,int y,double r,double h);  //修改数据
    double Area();  //计算表面积
    double Volume();  //计算体积
    void Print();
};
Cylinder::Cylinder(int x,int y,double r,double h):Circle(x,y,h)
{
    high=h;
}
void Cylinder::Set_data(int x,int y,double r,double h)
{
    SetPoint(x,y); //Point类的成员函数
    SetRadius(r);  //Circle类的成员函数
    high=h;
}
double Cylinder::Volume()
{
    return Circle::Area()*high;
}
double Cylinder::Area()
{
    double r=GetRadius();
    return 2*pi*r*r+2*pi*r*high;
}
int main( )
{
    Point p(30,50);
    p.Print();
    cout<<endl;
    Circle c(120,80,10.0);
    cout<<"圆心:";
    c.Point::Print();
    cout<<"\n圆面积"<<c.Area()<<endl;
    Cylinder cy(240,160,10.0,10.0);
    cout<<"圆柱体中心点:";
    cy.Point::Print();
    cout<<"\n圆柱体圆面积:"<<cy.Circle::Area()<<endl;
    cout<<"圆柱体表面积:"<<cy.Area()<<endl;
    cout<<"圆柱体体积:"<<cy.Volume()<<endl;
    return 0;
}



来自西安交通大学MOOC课件

    原文作者:thistle2012
    原文地址: https://blog.csdn.net/u013232740/article/details/46392569
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。