2021-01-19
作者:互联网
纯虚函数
,你可以定义一个抽象基类,只完成部分功能,未完成的功能交给派生类去实现(谁派生谁实现)。这部分未完成的功能,往往是基类不需要的,或者在基类中无法实现的。虽然抽象基类没有完成,但是却强制要求派生类完成”#include using namespace std;//线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){ }//矩形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_lenm_width + m_lenm_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; }int main(){ Line *p = new Cuboid(10, 20, 30); cout<<"The area of Cuboid is "<area()<<endl; cout<<"The volume of Cuboid is "<volume()<<endl; p = new Cube(15); cout<<"The area of Cube is "<area()<<endl; cout<<"The volume of Cube is "<volume()<<endl; return 0;}Line 类表示“线”,没有面积和体积,但它仍然定义了 area() 和 volume() 两个纯虚函数。这样的用意很明显:Line 类不需要被实例化,但是它为派生类提供了“约束条件”,派生类必须要实现这两个函数,完成计算面积和体积的功能,否则就不能实例化。
标签:01,area,19,float,len,height,width,2021,Cuboid 来源: https://blog.csdn.net/weixin_50866517/article/details/112853852