1、当缺省参数和virtual函数一起使用的时候一定要谨慎
基类虚函数中的缺省参数会覆盖子类缺省参数。
#include <iostream>
using namespace std;
class Base {
public:
virtual void func(int x , int y = 0) {
cout << "Base::func(" << x << " ," << y << ")" << endl;
}
};
class Derived1 : public Base {
public:
virtual void func(int x, int y) {
cout << "Derived1::func(" << x << " ," << y << ")" << endl;
}
};
class Derived2 : public Base {
public:
virtual void func(int x, int y = 1) {
cout << "Derived2::func(" << x << " ," << y << ")" << endl;
}
};
int main() {
Base* p1 = new Derived1();
Base* p2 = new Derived2();
p2->func(3);//Derived2::func(3 ,0)
p2->func(4);//Derived1::func(4 ,0),子类虚函数中的缺省参数被父类覆盖
}
输出结果:
Derived2::func(3 ,0)
Derived2::func(4 ,0)
Derived2::func(5 ,1)
可见,当用一个父类指针或引用指向子类对象,实现多态时,无论子类虚函数中的缺省值是什么,都会使用父类的缺省值。而子类指针指向子类对象则不受影响