重温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