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()调用派生类的。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短