为什么虚函数在编译期间无法确定下来?
struct Base
{
virtual void func()
{ std::cout << "Base::func()" << std::endl; }
};
struct Derived : Base
{
virtual void func()
{ std::cout << "Derived::func()" << std::endl; }
};
int main()
{
Base *bp = 0;
std::string input;
std::cin >> input;
if (input == "base")
bp = new Base;
else
bp = new Derived;
/* The compiler cannot decide which
function is called here: */
bp->func();
return 0;
}
看上面的代码就很容易知道,编译器无法在编译期判断 bp->func()
调用的是 Base::func()
还是 Derived::func()
,所以虚函数在编译期间是无法确定下来的。