定義 一個shape抽象類,派生出rectangle類和circle類,計算各類派生類物件的面積area().
#include<iostream> using namespace std; class shape{ public: virtual double area()=0; }; class rectangle:public shape{ public: rectangle(double w,double l):width(w),longth(l){ } double area(){ return (width*longth); } private: double width; double longth; }; class circle:public shape{ public: circle(double r):R(r){ } double area(){ return (3.14159*R*R); } private: double R; }; int main() { shape* shape1=new rectangle(4,7); shape* shape2=new circle(9); cout<<"長方形面積"<<shape1->area()<<endl; cout<<"圓形面積"<<shape2->area()<<endl; return 0; }
有一個交通工具類velicle,將它作為基類派生小車類car,卡車類truck和輪船類boat,定義這些類並定義一個虛擬函式用來顯示各類資訊。
1 *#include<iostream> 2 #include<string> 3 using namespace std; 4 class vehicle 5 { 6 public: 7 string name; 8 public: 9 vehicle(string h):name(h){ 10 } 11 virtual void showinfo() const{ 12 cout<<name<<endl; 13 } 14 }; 15 class Car: virtual public vehicle{ 16 public: 17 double speed; 18 double fuel; 19 public: 20 Car(string h):vehicle(h),speed(200),fuel(14.8){ 21 } 22 virtual void showinfo() const { 23 cout<<name<<endl; 24 cout<<speed<<"km/h"<<endl; 25 cout<<fuel<<"l/100kkm"<<endl;} 26 }; 27 class Truck:virtual public vehicle 28 {public: 29 double speed; 30 double fuel; 31 public: 32 Truck(string h):vehicle(h),speed(100),fuel(18.8){ 33 } 34 virtual void showinfo() const { 35 cout<<name<<endl; 36 cout<<speed<<"km/h"<<endl; 37 cout<<fuel<<"l/100kkm"<<endl; } 38 }; 39 class Boat:virtual public vehicle 40 { 41 public: 42 double speed; 43 double fuel; 44 public: 45 Boat(string h):vehicle(h),speed(40),fuel(8.8){ 46 } 47 virtual void showinfo() const { 48 cout<<name<<endl; 49 cout<<speed<<"km/h"<<endl; 50 cout<<fuel<<"l/100kkm"<<endl;} 51 }; 52 int main() 53 { 54 vehicle *vp; 55 string name0,name1,name2; 56 cin>>name0; 57 Car car(name0); 58 cin>>name1; 59 Truck truck(name1); 60 cin>>name2; 61 Boat boat(name2); 62 vp=&car; 63 vp->showinfo(); 64 vp=&truck; 65 vp->showinfo(); 66 vp=&boat; 67 vp->showinfo(); 68 return 0; 69 }