定義一個shape抽象類,在此基礎上派生出矩形rectangle和圓形circle類,
二者都有getPerim函數計算對象的周長。
getPerim函數是純虛函數,getName是虛函數。
如果不設定getName為虛函數那麼在進行指針調用這個函數的時候就不能調用派生類的相應函數了。
結果即為如圖:
正确運作結果為:
#include<iostream>
using namespace std;
#define PI 3.14159
class shape{
public:
virtual float getPerim() const =0;
virtual void getName()const{cout<<"shape:";}
shape(){}
~shape(){}
};
class Rectangle:public shape{
public:
Rectangle(){}
~Rectangle(){}
Rectangle(float l,float w):length(l),width(w){}
virtual float getPerim() const;
virtual void getName()const{cout<<"Rectangle:";}
private:
float length,width;
};
float Rectangle::getPerim() const{
return 2*(length+width);
}
class Circle :public shape{
public:
Circle(){}
Circle(float r):radius(r){}
~Circle(){}
virtual float getPerim()const;
virtual void getName()const{cout<<"Circle:";}
private:
float radius;
};
float Circle::getPerim()const{
return 2*PI*radius;
}
void main(){
shape *sp;
Circle circle(2.2);
Rectangle rectangle(1.5,6.6);
/*普通的通路方式,另一種是使用指針實作動态多态
circle.getName();
cout<<circle.getPerim()<<endl;
rectangle.getName();
cout<<rectangle.getPerim()<<endl;
*/
sp=&circle;
sp->getName();
cout<<sp->getPerim()<<endl;
sp=&rectangle;
sp->getName();
cout<<sp->getPerim()<<endl;
}