下面内容总结了关键字“virtual”使用的几个场合:
- 运用多态性;
多态性:C++继承机制中的一种技术,这种技术在程序运行时能一句其类型确认调用哪个函数的能力;
多态性又称 “迟后联编”,又称“滞后联编”。
使用例子:
1 #include<iostream.h> 2 3 class Base 4 { 5 public: 6 virtual void fn() //使用了关键字:virtual; 7 { 8 cout<<"In Base class "; 9 } 10 }; 11 12 class SubClass:public Base 13 { 14 public: 15 virtual void fn() //使用了关键字:virtual; 16 { 17 cout<<"In SubClass "; 18 } 19 }; 20 21 void test(Base& b) 22 { 23 b.fn(); 24 } 25 26 void main() 27 { 28 Base bc; 29 SubClass sc; 30 cout<<"Calling test(bc) "; 31 test(bc); 32 cout<<"Calling test(sc) "; 33 test(sc); 34 }
2. 抽象类;
严格说,这个条目从属于上面一条。
使用例子:
1 class Display 2 { 3 public: 4 virtual void init()=0; //使用了关键字:virtual; 5 virtual void write(char * pString); 6 };
3. 虚拟继承;
为解决多重继承模糊性问题而引入的虚拟继承技术;
使用例子:
1 #include<iostream.h> 2 3 class Furniture 4 { 5 public: 6 Furniture(){} 7 void SetWeight(int i){weight=i;} 8 int GetWeight(){return weight;} 9 protected: 10 int weight; 11 }; 12 13 class Bed:virtual public Furniture //使用了关键字:virtual; 14 { 15 public: 16 Bed(){} 17 void Sleep() 18 { 19 cout<<"Sleeping... "; 20 } 21 }; 22 23 class Sofa:virtual public Furniture //使用了关键字:virtual; 24 { 25 public: 26 Sofa(){} 27 void WatchTV() 28 { 29 cout<<"Watching TV. "; 30 } 31 }; 32 33 class SleeperSofa:public Bed, public Sofa 34 { 35 public: 36 SleeperSofa():Sofa(),Bed(){} 37 void FoldOut() 38 { 39 cout<<"Fold out the sofa. "; 40 } 41 }; 42 43 void main() 44 { 45 SleeperSofa ss; 46 ss.SetWeight(20); 47 cout<<ss.GetWeight()<<endl; 48 }