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() 被调用。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP