C++——从一个正方体类(Cube)和球体类(Sphere),派生出圆柱体类(Cylinder),设计成员函数,能够输出正方体、球体、圆柱体的面积和体积。
没注释的源代码
#include <iostream>
using namespace std;
class Cube
{
public:
Cube(int a):a(a){}
void Cube_area()
{
cout<<"正方体的面积:"<<a*a<<endl;
}
void Cube_tiji()
{
cout<<"正方体的体积:"<<a*a*a<<endl;
}
protected:
double a;
};
class Sphere
{
public:
Sphere(int r):r(r){}
void Sphere_area()
{
cout<<"球体的面积:"<<3.14*r*r*4<<endl;
}
void Sphere_tiji()
{
cout<<"球体的体积:"<<4/3*3.14*r*r*r<<endl;
}
protected:
double r;
};
class Cylinder:public Cube,public Sphere
{
public:
Cylinder(int a,int r):Cube(a),Sphere(r){}
void Cylinder_area()
{
cout<<"圆柱体的面积:"<<(3.14*r*r+a*a)*2<<endl;
}
void Cylinder_tiji()
{
cout<<"圆柱体的体积:"<<3.14*r*r*a<<endl;
}
};
int main()
{
Cube c1(3);
c1.Cube_area();
c1.Cube_tiji();
Sphere s1(5);
s1.Sphere_area();
s1.Sphere_tiji();
Cylinder c2(3,5);
c2.Cylinder_area();
c2.Cylinder_tiji();
return 0;
}