1. 程式人生 > >(C/C++學習心得)5.C++中的虛繼承-虛擬函式-多型解析

(C/C++學習心得)5.C++中的虛繼承-虛擬函式-多型解析

1 #include<iostream> 2 using namespace std; 3 4 class bed 5 { 6 public: 7 bed(float l,float wi,float we) 8 :len(l),wid(wi),weight(we) 9 {} 10 11 void sleep() 12 { 13 cout<<"go to sleep!!!!!"<<endl; 14 } 15 16 void dis() 17
{ 18 cout<<"len = "<<len<<endl; 19 cout<<"wid = "<<wid<<endl; 20 cout<<"weight = "<<weight<<endl; 21 } 22 protected: 23 float len; 24 float wid; 25 float weight; 26 }; 27 //+++++++++++++++++++++++++++++
28 class sofa 29 { 30 public: 31 sofa(float l,float wi,float we) 32 :len(l),wid(wi),weight(we) 33 {} 34 void sit() 35 { 36 cout<<"go to have a rest!!!!!"<<endl; 37 } 38 void dis() 39 { 40 cout<<"len = "<<len<<endl; 41
cout<<"wid = "<<wid<<endl; 42 cout<<"weight = "<<weight<<endl; 43 } 44 protected: 45 float len; 46 float wid; 47 float weight; 48 49 }; 50 //+++++++++++++++++++++++++++ 51 class sofabed:public bed,public sofa 52 { 53 public: 54 sofabed(float l,float wi,float we) 55 :bed(l,wi,we),sofa(l,wi,we) 56 {} 57 }; 58 //+++++++++++++++++++++++++++ 59 int main() 60 { 61 bed b(1,2,3); 62 b.sleep(); 63 b.dis(); 64 sofa s(2,3,4); 65 s.sit(); 66 s.dis(); 67 sofabed sb(5,6,7); 68 sb.sit(); 69 sb.sleep(); 70 sb.sofa::dis(); 71 sb.bed::dis(); 72 return 0; 73 }