使用类的继承和派生实现对矩形,正方形,三角形,圆形的定义,并实现对长方体,正方体,球体和圆锥的表面积、体积的计算。
#include <iostream>
#include <cmath>
using namespace std;
const float pi = 3.14;
class Line
{
public:
Line(float len) : m_len(len) {}
virtual float area() = 0;
virtual float volume() = 0;
protected:
float m_len;
};
class Tri : public Line
{
public:
Tri(float len, float height) : Line(len)
{
m_height = height;
}
float area()
{
return m_height * m_len / 2;
}
protected:
float m_height;
};
class Cir : public Line
{
public:
Cir(float len) : Line(len)
{
m_radius = len;
}
float area()
{
return m_radius * m_radius * pi;
}
protected:
float m_radius;
};
class Rec : public Line
{
public:
Rec(float len, float width) : Line(len)
{
m_width = width;
}
float area()
{
return m_width * m_len;
}
protected:
float m_width;
};
class Cuboid : public Rec
{
public:
Cuboid(float len, float width, float height) : Rec(len, width)
{
m_height = height;
}
float area()
{
return 2 * (m_len * m_width + m_len * m_height + m_width * m_height);
}
float volume()
{
return m_width * m_height * m_len;
}
protected:
float m_height;
};
class Cube : public Cuboid
{
public:
Cube(float len) : Cuboid(len, len, len) {}
};
class Cone : public Tri
{
public:
Cone(float radius, float height) : Tri(radius, height)
{
m_radius = radius;
m_height = height;
}
float area()
{
return (pi * sqrt(m_radius * m_radius + m_height * m_height) * m_radius + pi * m_radius * m_radius);
}
float volume()
{
return pi * m_radius * m_radius * m_height / 3;
}
protected:
float m_radius;
float m_height;
};
class Sph : public Line
{
public:
Sph(float len) : Line(len)
{
m_radius = len;
}
float area()
{
return 4 * pi * m_radius * m_radius;
}
float volume()
{
return 4 / 3 * pi * m_radius * m_radius * m_radius;
}
protected:
float m_radius;
};
int main()
{
Line *p = new Cuboid(1, 2, 3);
cout << "长方体的表面积是" << p->area() << endl;
cout << "长方体的体积是" << p->volume() << endl;
delete p;
p = new Cube(3);
cout << "正方体的表面积是" << p->area() << endl;
cout << "正方体的体积是" << p->volume() << endl;
delete p;
p = new Cone(3, 4);
cout << "圆锥的表面积是" << p->area() << endl;
cout << "圆锥的体积是" << p->volume() << endl;
delete p;
p = new Sph(3);
cout << "球体的表面积是" << p->area() << endl;
cout << "球体的体积是" << p->volume() << endl;
delete p;
return 0;
}
|