virtual 返回值類型 函數名 (函數參數) = 0;
純虛函數沒有函數體,只有函數聲明,在虛函數聲明的結尾加上=0
,表明此函數為純虛函數。
最後的=0
並不表示函數返回值為0,它只起形式上的作用,告訴編譯系統“這是純虛函數”。
包含純虛函數的類稱為抽象類(Abstract Class)。之所以說它抽象,是因為它無法實例化,也就是無法創建對象。原因很明顯,純虛函數沒有函數體,不是完整的函數,無法調用,也無法為其分配內存空間。#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 *p = new Cuboid(10, 20, 30); cout<<"The area of Cuboid is "<<p->area()<<endl; cout<<"The volume of Cuboid is "<<p->volume()<<endl; p = new Cube(15); cout<<"The area of Cube is "<<p->area()<<endl; cout<<"The volume of Cube is "<<p->volume()<<endl; return 0; }運行結果:
//頂層函數不能被聲明為純虛函數 void fun() = 0; //compile error class base{ public : //普通成員函數不能被聲明為純虛函數 void display() = 0; //compile error };