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