纯虚函数

  1 #include<iostream> 
  2 using namespace std; 
  3 class shape{//图形类 
  4     public: 
  5         virtual double area() = 0;//纯虚函数 
  6 }; 
  7 class rect:public shape{ 
  8 int ma; 
  9 int mb; 
 10     public: 
 11     rect(int a,int b){//构造函数 
 12         ma = a; 
 13         mb = b; 
 14     } 
 15     double area(){ 
 16         return ma*mb; 
 17     } 
 18 }; 
 19 class circle:public shape{ 
 20 int mr; 
 21     public: 
 22         circle(int r){ 
 23             mr = r; 
 24         } 
 25         double area(){ 
 26             return 3.14*mr*mr; 
 27         } 
 28 }; 
 29 void area(shape*p){//纯虚函数抽象类不能定义对象,抽象类能够定义指针 
 30     //该指针指向抽象类的子类,抽象类的子类肯定会把纯虚函数实现了 
 31     //通过抽象类的指针调用纯虚函数的语句是编译运行过的 
 32     double r = p->area(); 
 33     cout << "r=" << r << endl; 
 34 }

rect r(4,4)=16
circle c(5)=78.5
r=16
r=78.5

原文地址:https://www.cnblogs.com/DXGG-Bond/p/11979456.html