動的バインディングはvpointerとvtableを使用しています。ただし、動的バインディングは関数ポインタにのみ適用されます。動的バインド引数のメカニズムはありません。
したがって、デフォルトの引数はコンパイラ時に静的に決定されます。この場合、Baseクラスへのポインタであるbp型によって静的に決定されます。したがって、data = 10は関数引数として渡され、関数ポインタはDerivedクラスメンバ関数:D :: printを指しています。基本的には、D :: print(10)を呼び出します。
次のコードスニペットと結果の出力は、派生呼び出しメンバ関数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
答えはあなたの問題を解決(またはあなたがそれを理解します)場合は、答えの左側にある緑色のチェックマークを使用して、それを受け入れてください。 –