1 /* 2 面向对象: 3 多态, 4 继承 5 封装 6 */ 7 #include <stdio.h> 8 #include <stdlib.h> 9 10 //一旦有了纯虚函数,该对象就不能实例化了. 11 #define USE_PURE_VIRTUAL_FUNC 1 12 13 class CBase 14 { 15 public: 16 CBase(){} 17 ~CBase(){} 18 public: 19 void doA()//不标virtual,说明不想被子类重载,如果遇到基类对象指针,则使用该函数时永远是用基类的 20 { 21 printf("call %s\n",__FUNCTION__); 22 } 23 virtual void doB() 24 { 25 printf("call %s\n",__FUNCTION__); 26 } 27 #if USE_PURE_VIRTUAL_FUNC > 0 28 virtual void doC() = 0;//父类不实现,但子类必须实现. 29 #endif 30 31 }; 32 33 class CChild:public CBase 34 { 35 public: 36 CChild():CBase() 37 {}; 38 ~CChild(){}; 39 public: 40 void doA() 41 { 42 printf("child call doA\n"); 43 } 44 virtual void doB() 45 { 46 printf("child call doB\n"); 47 } 48 #if USE_PURE_VIRTUAL_FUNC > 0 49 virtual void doC() 50 { 51 printf("child call doC\n"); 52 } 53 #endif 54 }; 55 56 int main(void) 57 { 58 #if USE_PURE_VIRTUAL_FUNC <= 0 59 CBase* pB = new CBase(); 60 CChild* pC = new CChild(); 61 62 63 pB->doA(); 64 pB->doB(); 65 66 pC->doA(); 67 pC->doB(); 68 69 70 CBase* pTemp = pB; 71 pTemp->doA(); 72 pTemp->doB(); 73 74 75 pTemp = pC; 76 pTemp->doA(); 77 pTemp->doB(); 78 79 delete pB; 80 delete pC; 81 #else 82 CChild* pC = new CChild(); 83 84 85 pC->doA(); 86 pC->doB(); 87 88 89 CBase* pTemp = NULL; 90 pTemp = pC; 91 pTemp->doA(); 92 pTemp->doB(); 93 pTemp->doC(); 94 95 delete pC; 96 #endif 97 98 99 100 101 return 0; 102 }
时间: 2024-09-29 18:01:28