动态绑定使用vpointer和vtable。但是,动态绑定仅适用于函数指针。没有动态绑定参数的机制。
因此,默认参数是在编译器时间静态确定的。在这种情况下,它是由bp类型静态确定的,这是一个指向Base类的指针。因此data = 10作为函数参数传递,而函数指针指向派生类成员函数:D :: print。本质上,它调用D :: print(10)。
以下代码片段和结果输出清楚地表明了一点:即使它调用Derived call成员函数Derived :: resize(int),它也会传递Base类的默认参数:size = 0。
虚拟无效衍生::调整大小(int)的大小为0
#include <iostream>
#include <stdio.h>
using namespace std;
#define pr_dbgc(fmt,args...) \
printf("%d %s " fmt "\n",__LINE__,__PRETTY_FUNCTION__, ##args);
class Base {
public:
virtual void resize(int size=0){
pr_dbgc("size %d",size);
}
};
class Derived : public Base {
public:
void resize(int size=3){
pr_dbgc("size %d",size);
}
};
int main()
{
Base * base_p = new Base;
Derived * derived_p = new Derived;
base_p->resize(); /* calling base member function
resize with default
argument value --- size 0 */
derived_p->resize(); /* calling derived member
function resize with default
argument default --- size 3 */
base_p = derived_p; /* dynamic binding using vpointer
and vtable */
/* however, this dynamic binding only
applied to function pointer.
There is no mechanism to dynamic
binding argument. */
/* So, the default argument is determined
statically by base_p type,
which is pointer to base class. Thus
size = 0 is passed as function
argument */
base_p->resize(); /* polymorphism: calling derived class
member function
however with base member function
default value 0 --- size 0 */
return 0;
}
#if 0
The following shows the outputs:
17 virtual void Base::resize(int) size 0
24 virtual void Derived::resize(int) size 3
24 virtual void Derived::resize(int) size 0
#endif
如果答案解决您的问题(或者让你了解它),请接受它,使用上的答案左侧的绿色的勾。 –