面向对象程序设计3--简单

//

//  main.cpp

//  circlec++

//

//  Created by duanqibo on 2019/7/12.

//  Copyright © 2019年 duanqibo. All rights reserved.

//

#include <iostream>

using namespace std;

const double PI=3.14159;

class circle

{

private:

    double radius;

public:

    circle(double r)

    {

        radius=r;

    }

    virtual double area()

    {

        return 0.0;

    }

    

    virtual double volume()

    {

        return 0.0;

    }

    

    double getRadius()

    {

        return radius;

    }

};

class sphere:public circle

{

public:

    sphere(double r):circle(r){};

    

    double area()

    {

        return 4.0*PI*getRadius()*getRadius();

    }

    double volume()

    {

        return 4.0*PI*getRadius()*getRadius()*getRadius()/3;

    }

};

class column:public circle

{

private:

    double height;

public:

    column(double r,double h):circle(r)

    {

        height=h;

    }

    double area()

    {

        return 2.0*PI*getRadius()*(getRadius()+height);

    }

    double volume()

    {

        return PI*getRadius()*getRadius()*height;

    }

};

int main(int argc, const char * argv[])

{

    circle *p;

    sphere sobj(2.0);

    p=&sobj;

    /////////////////////////////

    cout<<"球体:"<<endl;

    cout<<"球体体积:"<<p->volume()<<endl;

    cout<<"球体表面积:"<<p->area()<<endl;

    /////////////////////////////

    column cobj(3,5);

    p=&cobj;

    cout<<"圆柱体:"<<endl;

    cout<<"圆柱体体积:"<<p->volume()<<endl;

    cout<<"圆柱体表面积:"<<p->area()<<endl;

    

    return 1;

}

运行结果:

原文地址:https://www.cnblogs.com/duanqibo/p/11177117.html