C ++中的默认参数和虚函数

让我们考虑一下C ++中的示例程序,以便于理解该概念-

范例程式码

#include<iostream>
using namespace std;
class B {
   public:
      virtual void s(int a = 0) {
         cout<<" In Base \n";
      }
};
class D: public B {
   public:
      virtual void s(int a) {
         cout<<"In Derived, a="<<a;
      }
};
int main(void) {
   D d; // An object of class D
   B *b= &d;// A pointer of type B* pointing to d
   b->s();// prints"D::s() called"
   return 0;
}

输出结果

In Derived, a = 0

在此输出中,我们观察到s()调用了派生类,并使用了基类的默认值s()

默认参数不参与函数签名。因此s(),基类和派生类中的签名被视为相同,因此基类的签名s()被覆盖。默认值在编译时使用。当编译器检查函数调用中缺少参数时,它将替换给定的默认值。因此,在上述程序中,x的值在编译时被替换,并在运行时s()调用派生类。a的值在编译时被替换,并在运行时s()调用派生类的。