C++中,将虚函数声明为纯虚函数的格式为:
virtual 返回值类型 函数名(参数列表)= 0;
包含纯虚函数的类称为抽象类,抽象类不可实例化,无法创建对象。因为纯虚函数没有函数体,是不完整的,无法调用,无法分配内存。
抽象类通常是基类,让派生类去实现纯虚函数。派生类必须实现纯虚函数才能实例化。
#include<iostream> 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_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; } int main() { // Line *pl=new Rec(2,5); // cout<<pl->Area()<<endl; // delete pl; // cout<<"---------------------"<<endl; Line *p2= new Cuboid(2,3,4); cout<<p2->Area()<<","<<p2->Volume()<<endl; delete p2; cout<<"---------------------"<<endl; Line *pc = new Cube(2); cout<<pc->Area()<<","<<pc->Volume()<<endl; delete pc; }
本例中定义了四个类,它们的继承关系为:Line --> Rec --> Cuboid --> Cube。
Line 是一个抽象类,也是最顶层的基类,在 Line 类中定义了两个纯虚函数 area() 和 volume()。
在 Rec 类中,实现了 area() 函数;所谓实现,就是定义了纯虚函数的函数体。但这时 Rec 仍不能被实例化,因为它没有实现继承来的 volume() 函数,volume() 仍然是纯虚函数,所以 Rec 也仍然是抽象类。
直到 Cuboid 类,才实现了 volume() 函数,才是一个完整的类,才可以被实例化。
原文:https://www.cnblogs.com/njit-sam/p/13231514.html