不要忘记最后那个 default 分支。
即使程序真的不需要 default 处理, 也应该保留语句 default : break; 这样做并非多此一举,而是为了防止别人误以 为你忘了 default 处理。
1 #include <iostream> 2 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 Base { 7 public: 8 //定义两个虚函数 9 virtual void aFn1(void){ 10 cout<<"aFnl is in Base class."<<endl; 11 } 12 virtual void aFn2(void) { 13 cout<<"aFn2 is in Base class."<<endl; 14 } 15 //定义非虚函数 16 void aFn3(void) { 17 cout<<"aFn3 is in Base class."<<endl; 18 } 19 }; 20 21 //派生类Derived_1中重新定义了基类中的虚函数aFn1 22 class Derived_1:public Base 23 { 24 public: 25 void aFn1(void) { //覆盖aFn1()函数 26 cout<<"aFnl is in First derived class."<<endl; 27 } 28 // void aFn3(void) { 语法错误 29 // cout<<"aFn3 is in First derived class."<<endl; 30 //} 31 }; 32 33 //派生类Derived_2中重新定义了基类中的虚函数aFn2 34 class Derived_2:public Base{ 35 public: 36 void aFn2(void){ //覆盖aFn2()函数 37 cout<<"aFn2 is in Second derived class."<<endl; 38 } 39 // void aFn3(void) { 语法错误 40 // cout<<"aFn3 is in Second derived class."<<endl; 41 //} 42 }; 43 //main()函数的定义 44 45 int main(int argc, char** argv) { 46 47 //创建和使用基类Base的对象 48 Base b; 49 cout<<"Base:"<<endl; 50 b.aFn1(); 51 b.aFn2(); 52 b.aFn3(); 53 cout<<"----------------------"<<endl; 54 55 //创建和使用派生类Derived_1的对象 56 Derived_1 d1; 57 cout<<"Derived_1:"<<endl; 58 d1.aFn1(); 59 d1.aFn2(); 60 d1.aFn3(); 61 cout<<"----------------------"<<endl; 62 63 //创建和使用派生类Derived_2的对象 64 Derived_2 d2; 65 cout<<"Derived_2:"<<endl; 66 d2.aFn1(); 67 d2.aFn2(); 68 d2.aFn3(); 69 return 0; 70 }