绝不重新定义继承而来的缺省参数值

重温Effective c++

Item 37,Never redefine a function's inherited default parameter value.


 虚函数的调用,以及VFP的实现机制,应该已经很清楚了。

虚函数通过动态绑定,在通过指针和引用调用的时候,通过实际指向的对象的虚函数列表得到要调用的函数的地址。


但是一直不清楚的是,如果派生类重新定义了虚函数默认参数,这种重新定义是没有效果的。


原因是,c++对函数的默认参数是通过静态绑定的,也就是说调用的时候,会根据指针的类型(而不是指针指向的对象的类型)取得静态绑定的参数。




 
 
  1. #include<string>
  2. #include<list>
  3. #include<iostream>
  4. //#include<boost/shared_ptr.hpp>
  5. #include<math.h>
  6. using namespace std;
  7. class Base
  8. {
  9. public:
  10. virtual void print(string val="Base")
  11. {
  12. cout<< "this is class base print "<<val<< endl;
  13. }
  14. };
  15. class Derive: public Base
  16. {
  17. public:
  18. virtual void print(string val="Derive")
  19. {
  20. cout<< "this is class derive print "<<val<< endl;
  21. }
  22. };
  23. int main()
  24. {
  25. Base *p= new Derive();
  26. p->print();
  27. return 0;
  28. }

输出结果:

AlexdeMacBook-Pro:~ alex$ a.out
this is class derive print Base


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值