虚基类的简单应用举例
1 #include <iostream> 2 #include <string.h> 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 4 using namespace std; 5 6 class Person 7 { 8 public: 9 Person(string nam,char s,int a) 10 { 11 name=nam; 12 sex=s; 13 age=a; 14 } 15 protected: 16 string name; 17 char sex; 18 int age; 19 }; 20 21 class Teacher:virtual public Person 22 { 23 public: 24 Teacher(string nam,char s,int a,string t):Person(nam,s,a) 25 { 26 title=t; 27 } 28 protected: 29 string title; 30 }; 31 32 class Student:virtual public Person 33 { 34 public: 35 Student(string nam,char s,int a,float sco) 36 :Person(nam,s,a),score(sco){ 37 38 } 39 protected: 40 float score; 41 }; 42 43 class Graduate:public Teacher,public Student 44 { 45 public: 46 Graduate(string nam,char s,int a,string t,float sco,float w) 47 :Person(nam,s,a),Teacher(nam,s,a,t),Student(nam,s,a,sco),wage(w){ 48 49 } 50 void show() 51 { 52 cout<<"name:"<<name<<endl; 53 cout<<"age:"<<age<<endl; 54 cout<<"sex:"<<sex<<endl; 55 cout<<"score:"<<score<<endl; 56 cout<<"title:"<<title<<endl; 57 cout<<"wages:"<<wage<<endl; 58 } 59 private: 60 float wage; 61 }; 62 int main(int argc, char** argv) { 63 Graduate grad1("wang",'f',24,"assistant",99,123); 64 grad1.show(); 65 return 0; 66 }