假设有如下类:
1 class Base { 2 public: 3 virtual void disp(int x = 3) {//虚函数带默认参数值,3 4 cout << "Base::x is " << x << endl; 5 } 6 }; 7 class Derived: public Base { 8 public: 9 virtual void disp(int x = 100) {//子类重定义了默认参数值,100 10 cout << "Derived::x is " << x << endl; 11 } 12 }; 13 14 Base* ins = new Derived(); 15 ins->disp();
地球人都知道,将调用Derived的disp函数
但是,实际结果有点偏差:
Derived::x is 3
虽然调用了调用Derived的disp函数,但默认参数使用的是Base类的???这是因为默认参数是静态绑定的,Base *ins将使用Base的disp默认参数,即x=3
规避
保持默认参数值的一致