C++中的缺省参数和虚函数

让我们首先了解默认参数和虚拟函数的含义。

null

默认参数: 这些是在函数声明期间提供的值,因此,如果没有参数传递给这些值,则可以自动分配这些值。如果传递了任何值,则会覆盖默认值。

虚拟功能: 虚函数是在基类中声明并由派生类重新定义(重写)的成员函数。当使用指针或基类引用引用派生类对象时,可以为该对象调用虚拟函数并执行派生类版本的函数。

若要查看默认参数与虚拟函数的组合应用,首先可以查看下面的C++程序,

CPP

// CPP program to demonstrate how default arguments and
// virtual function are used together
#include <iostream>
using namespace std;
class Base {
public :
virtual void fun( int x = 0)
{
cout << "Base::fun(), x = " << x << endl;
}
};
class Derived : public Base {
public :
virtual void fun( int x)
{
cout << "Derived::fun(), x = " << x << endl;
}
};
// Driver Code
int main()
{
Derived d1;
Base* bp = &d1;
bp->fun();
return 0;
}


输出

Derived::fun(), x = 0

如果我们仔细观察输出,就会发现调用了派生类的fun(),并使用了基类fun()的默认值。 默认参数不参与函数的签名。因此基类和派生类中fun()的签名被认为是相同的,因此基类的fun()被覆盖。此外,默认值在编译时使用。当编译器发现函数调用中缺少参数时,它会替换给定的默认值。因此,在上面的程序中,x的值在编译时被替换,并且在运行时调用派生类的fun()。

现在预测以下程序的输出,

CPP

// CPP program to demonstrate how default arguments and
// virtual function are used together
#include <iostream>
using namespace std;
class Base {
public :
virtual void fun( int x = 0)
{
cout << "Base::fun(), x = " << x << endl;
}
};
class Derived : public Base {
public :
virtual void fun( int x = 10) // NOTE THIS CHANGE
{
cout << "Derived::fun(), x = " << x << endl;
}
};
int main()
{
Derived d1;
Base* bp = &d1;
bp->fun();
return 0;
}


输出

Derived::fun(), x = 0

此程序的输出与上一个程序相同。原因是相同的,默认值在编译时被替换。fun()是在“bp”上调用的,它是基类型的指针。所以编译器替换0(不是10)。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享