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()调用派生类的。
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿