動態綁定使用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
如果答案解決您的問題(或者讓你瞭解它),請接受它,使用上的答案左側的綠色的勾。 –