我正在学习 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;
}