在C++编译器中,默认参数是静态绑定的。
对于函数
void func(int x, int y = 2);
如果在程序中出现func(1)调用。编译器会生成类似如下代码:
push 2;//默认参数
push 1;//x的参数值
call func
测试代码:
#include<iostream>
using namespace std;
class Base
{
public:
virtual void f(int x = 1) {cout<<"Base: "<<x<<endl;}
};
class Derived: public Base
{
public:
virtual void f(int x = 2) {cout<<"Derived: "<<x<<endl;}
};
int main()
{
Base * btr = new Derived();
btr->f();
return 0;
}
输出:
Derived: 1
分析:
因为通过基类指针btr调用f,所以编译器会选择基类中指定的默认参数1。
2443

被折叠的 条评论
为什么被折叠?



