考虑以下示例代码:
class Base {
public:
void f();
virtual void vf();
};
class Derived : public Base {
public:
void f();
void vf();
};
#include <iostream>
using namespace std;
void Base::f() {
cout << "Base f()" << endl;
}
void Base::vf() {
cout << "Base vf()" << endl;
}
void Derived::f() {
cout << "Derived f()" << endl;
}
void Derived::vf() {
cout << "Derived vf()" << endl;
}
int main()
{
Base b1;
Derived d1;
b1.f();
b1.vf();
d1.f();
d1.vf();
Derived d2; // Derived object
Base* bp = &d2; // Base pointer to Derived object
bp->f(); // Base f()
bp->vf(); // which vf()?
return 0;
}
运行的输出是:
Base f()
Base vf()
Derived f()
Derived vf()
Base f()
Derived vf()
问题:
在该行
Base* bp = &d2
中,对象类型在编译时是已知的。那么在这种情况下使用哪个函数bp->vf();
也可以在编译时做出决定对吗?由于对象类型在编译时本身是已知的,那么这个示例程序中是否使用了虚函数的强大功能?