#include <iostream>
using namespace std;
//线
//Line是抽象类,也是最顶层的基类
class Line{
public:
Line(float len); //构造函数
virtual float area() = 0;
virtual float volume() = 0;
protected:
float m_len;
};
Line::Line(float len): m_len(len){ }
//矩形
//实现了area()函数(就是定义了纯虚函数的函数体)。没有实现纯虚函数volume(),Rec仍然是抽象类
class Rec: public Line{
public:
Rec(float len, float width); //构造函数
float area();
protected:
float m_width;
};
Rec::Rec(float len, float width): Line(len), m_width(width){ }
float Rec::area(){ return m_len * m_width; }
//长方体
//不是抽象类,可以被实例化
class Cuboid: public Rec{
public:
Cuboid(float len, float width, float height); //构造函数
float area();
float volume();
protected:
float m_height;
};
Cuboid::Cuboid(float len, float width, float height): Rec(len, width), m_height(height){ }
float Cuboid::area(){ return 2 * ( m_len*m_width + m_len*m_height + m_width*m_height); }
float Cuboid::volume(){ return m_len * m_width * m_height; }
//正方体
class Cube: public Cuboid{
public:
Cube(float len); //构造函数
float area();
float volume();
};
Cube::Cube(float len): Cuboid(len, len, len){ }
float Cube::area(){ return 6 * m_len * m_len; }
float Cube::volume(){ return m_len * m_len * m_len; }
//继承关系:Line --> Rec --> Cuboid --> Cube
int main(){
Line *p = new Cuboid(10, 20, 30); //基类指针指向派生类Cuboid
cout<<"The area of Cuboid is "<<p->area()<<endl;
cout<<"The volume of Cuboid is "<<p->volume()<<endl;
p = new Cube(15); //基类指针指向Cube
cout<<"The area of Cube is "<<p->area()<<endl;
cout<<"The volume of Cube is "<<p->volume()<<endl;
return 0;
}
/*运行结果:*/
The area of Cuboid is 2200
The volume of Cuboid is 6000
The area of Cube is 1350
The volume of Cube is 3375
原文:https://www.cnblogs.com/xiaobaizzz/p/12334945.html