我正在学习C++中的虚函数和虚表。但是,我不明白为什么需要动态绑定(bind)。编译器是否不具备所有信息来确定函数调用是针对派生函数还是针对基本函数,例如:
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;
}
最佳答案
它可以。并且一些编译器会将调用转换为静态绑定(bind)。
在其他情况下,编译器必须使用动态绑定(bind)。
该函数应调用哪个foo()
?
void function( Base* p )
{
p->foo();
}
无法确定*。必须使用动态绑定(bind)。
*编辑:根据我提供的信息。 :)