参考此程序:
class A
{
public:
virtual void func(int i =1)
{
std::cout << "A->" << i << std::endl;
}
virtual void test()
{
func();
}
};
class B : public A
{
void func(int i =0)
{
std::cout << "B-> " << i << std::endl;
}
};
int main()
{
B *p = new B;
p->test();
return 0;
}
需要注意:virtual函数是动态绑定,但是缺省参数值却是静态绑定。
p->test();在执行时过程如下:
1:由于B没有重写test函数,需调用A中test();
2:A中test()中调用func();此函数还是virtual函数,由于p的动态类型是B*,所以调用B中的func(),输出"B->",当执行i参数时,缺省参数值时静态绑定,使用A中的缺省参数值,在编译阶段,i已经绑定,值为1;
3:输出为B->1,若在A中test()调用func(X) //X为某个值,此时调用的就是B中的func()中的i。
4:因此,不能重新定义继承而来的缺省参数值。