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

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

#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课件

  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值