摘要:多态性提供一组统一的调用接口函数,依据这些条用接口函数具体对象的不同,同一名字的函数会有不同的行为。
1、重载与隐藏
(1)、对同一作用域中的同名函数,如果它们的函数特征标不同,那么它们就形成一种重载关系。
(2)、基类与派生类中非虚同名函数,不管它们的参数特征标是否相同,它们都形成隐藏关系,即派生类对象隐藏基类中的同名函数。
1 #include <iostream> 2 3 using namespace std; 4 5 class Animal 6 { 7 public: 8 void walk() 9 { 10 cout << "Animal walk.\n"; 11 } 12 void walk(int walkWay) 13 { 14 switch(walkWay) 15 { 16 case 0: 17 cout << "Animal jump...\n"; 18 break; 19 case 1: 20 cout << "Animal fly...\n"; 21 break; 22 default: 23 cout << "Animal scrawling...\n"; 24 } 25 } 26 void sleep() 27 { 28 cout << "Animal sleeping..." << endl; 29 } 30 }; 31 class Human:public Animal 32 { 33 public: 34 void sleep() 35 { 36 cout << "Human sleep, lying...\n"; 37 } 38 }; 39 40 int main() 41 { 42 Animal *pAnimal = NULL; 43 Animal animal; 44 Human human; 45 46 pAnimal = &animal; 47 pAnimal->sleep(); 48 49 pAnimal = &human; 50 pAnimal->sleep(); 51 52 Human *pHuman = &human; 53 pHuman->sleep(); 54 55 pHuman->walk(1); 56 pHuman->walk(); 57 58 int c; 59 cin >> c; 60 return 0; 61 }