2

C++ の仮想関数と仮想テーブルについて学習しています。しかし、なぜ動的バインディングが必要なのか理解できませんでした。コンパイラーには、関数呼び出しが派生関数用か基本関数用かを判断するためのすべての情報がありません。たとえば、次のようになります。

class Base1 { 
   public : virtual void foo() 
            {  cout << " Base foo \n"; } 
};

class Base2 {
   public : virtual void foo() 
           { cout << " Base2 foo \n"; } 
};

class derived : public base1, base 2 {
     public : virtual void foo() 
       { cout << " derived foo \n"; }
}

int main()
{
  derived d;
  Base2 *p = &d;
  p->foo();       // why can't the compiler figure out that this
                  // is a function call to the derived function
                  // foo at compile time?

  return 0;
}
4

1 に答える 1

3

これがランタイム自体のコンパイル中に派生関数 foo への関数呼び出しであるという図をコンパイルできないのはなぜですか?

できる。また、一部のコンパイラその呼び出しを静的バインディングに変換します。

また、コンパイラが動的バインディングを使用する必要があるシナリオは他にもあります。

foo()この関数で呼び出されるのはどれですか?

void function( Base* p )
{
  p->foo();
}

断定できません*。動的バインディングを使用する必要があります。

*編集:私が提供した情報に基づいています。:)

于 2013-02-28T23:18:48.737 に答える