分享

覆盖(重写) vs 重载 vs 重定义

 XX_YY_ZZ 2015-11-02

重写(override),重载(overload),重定义(redefine)的区别
参见:http://www.cnblogs.com/BeyondTechnology/archive/2010/09/20/1831441.html

 

重写又称为覆盖,是指父类的虚函数在子类中被重写(覆盖),返回值和参数列表相同。

一般来说,如果父类的某个函数用virtual修饰,即使派生类中的同名函数没有用virtual修饰,只有满足下列条件,派生类的该函数也是虚函数:

函数名字相同,参数列表相同(个数和类型),返回值相同或者满足类型兼容规则。

 

重定义是指对父类的函数(不是virtual修饰的)重新定义。

 

重载是指具有相同的函数名,不同的参数列表(必须不同)的函数。(与返回值无关)

 

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Base  
  5. {  
  6. public:  
  7. //重载  
  8. //函数名相同,参数列表(参数个数或者类型)不同,与返回值无关  
  9. void fun1(int a){cout<<a<<endl;}  
  10. void fun1(double a){cout<<a<<" double "<<endl;}  
  11.   
  12. void fun2(int a,int b){cout<<"fun2() of Base!"<<endl;}  
  13.   
  14. virtual void fun3(){cout<<"virtual void fun3() of Base"<<endl;}  
  15. };  
  16.   
  17. class Derived:public Base  
  18. {  
  19. public:  
  20. void fun2(int a,int b){cout<<"fun2() of Derived!"<<endl;} //重定义父类的fun2()函数  
  21.   
  22. virtual void fun3(){cout<<"void fun3() of Derived!"<<endl;} //覆盖(重写)父类的fun3()函数  
  23. };  
  24.   
  25. int _tmain(int argc, _TCHAR* argv[])  
  26. {  
  27. Base* b1=new Base;  
  28.   
  29. b1->fun1(1);  
  30. b1->fun1(1.0);  
  31. b1->fun2(1,2);  
  32. b1->fun3();  
  33.   
  34. Base* b2=new Derived; //父类的指针指向子类的对象  
  35.   
  36. b2->fun1(1);  
  37. b2->fun1(1.0);  
  38. b2->fun2(1,2); //实际调用的是父类的,因为没有使用virtual  
  39. b2->fun3();  
  40.   
  41. return 0;  
  42. }  

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多