绝不重新定义继承而来的缺省参数值--from Effective c++ item 37

重温Effective c++

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


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

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


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


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



#include<string>
#include<list>
#include<iostream>
//#include<boost/shared_ptr.hpp>
#include<math.h>

using namespace std;
class Base
{
	public:
		virtual void print(string val="Base")
		{
			cout<<"this is class base print "<<val<<endl;	
		}
};

class Derive:public Base
{
	public:
		virtual void print(string val="Derive")
		{
			cout<<"this is class derive print "<<val<<endl;
		}
};




int main()
{
 Base *p=new Derive();
 p->print(); 
 return 0;
}

输出结果:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值