c++继承动态编写求 圆,球和圆柱的表面积和体积的程序

2025-04-16 10:36:42
推荐回答(1个)
回答1:

#include 
using namespace std;

const double PI = 3.14159265359;

class Sphere {
    protected:
        double radius;
    public:
        Sphere ( double r ) : radius( r ) {}
        void print_info() { cout << this->cal() << '\n'; }
        
    //    abstract class
        virtual double cal() = 0;
};

class Sph_surface : public Sphere {
    public:
        Sph_surface( double r ) : Sphere( r ) {}
        
        double cal() { return 4.0*PI*radius*radius; }
};

class Sph_volume : public Sphere {
    public:
        Sph_volume( double r ) : Sphere( r ) {}
        
        double cal() { return 4.0/3.0*PI*radius*radius*radius; }
};

int main(int argc, char *argv[]) {
    
    Sph_surface sph_1( 2.5 );
    sph_1.print_info();
    
    Sphere *sph_2 = new Sph_volume( 2.5 );
    sph_2->print_info();    
    delete sph_2;
    
    return 0;
}