main 下面输出的答案是“derived class display with i=10”,但我不明白为什么?该函数肯定是在基类型上调用的吗?
在这里确定答案的思考过程是什么?
class base
{
public:
virtual void display(int i = 10)
{
cout<<"Base class display with i = "<<i<<endl;
}
};
class derived : public base
{
public:
void display(int i = 20)
{
cout<<"Derived class display with i = "<< i <<endl;
}
};
int main(int argc, char *argv[])
{
base *bptr = new derived;
bptr->display();
return 0;
}
最佳答案
看看Can virtual functions have default parameters? :
A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.
因此,bptr->display();
调用了 display
的派生版本,但使用了 base
的参数,静态类型指针 bptr
。
这是因为参数的默认值必须在编译时确定,而动态绑定(bind)则推迟到运行时。在同一虚拟的基础版本和派生版本中使用不同的默认参数几乎肯定会造成麻烦。当virtual是通过引用或者指向base的指针调用的时候很可能会出现问题,但是执行的版本是derived定义的版本。在这种情况下,为虚拟的基本版本定义的默认参数将传递给派生版本,派生版本是使用不同的默认参数定义的。
关于c++ - 静态基类型和动态派生类型的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18066846/