多态 子类函数重写
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 class boss{ 5 public: 6 int fight(){ 7 int ret = 10; 8 cout << "boss::fight():ret=" << ret << endl; 9 return ret; 10 } 11 }; 12 class master{ 13 public: 14 virtual int eight(){ 15 int ret = 8; 16 cout << "master::eight():ret=" << ret << endl; 17 return ret; 18 } 19 }; 20 class newmaster:public master{ 21 public: 22 int eight(){ 23 int ret = master::eight()*2; 24 cout << "newmaster:eight():" << ret << endl; 25 return ret; 26 } 27 }; 28 void pk(master*master,boss*boss){ 29 int k = master->eight(); 30 int b = boss->fight(); 31 if(k < b){ 32 cout << "boss big" << endl; 33 }else{ 34 cout << "master big" << endl; 35 } 36 } 37 int main(){ 38 boss b; 39 newmaster n; 40 pk(&n,&b); 41 return 0; 42 }
打印结果:
master::eight():ret=8// 这行是第23的master::eight()产生的。
newmaster:eight():16
boss::fight():ret=10
master big
//多态时候会将父 类被重写的函数也执行