一、测试代码如下:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void out() {
cout << "Base::out()" << endl; }
void in() {
cout << "Base::in()" << endl; }
};
class Derived : public Base
{
public:
virtual void out() {
cout << "Derived::out()" << endl; }
void in() {
cout << "Derived::in()" << endl; }
};
int main()
{
Base* base = new Derived;
base->out(); // Derived::out()
base->in(); // Base::in()
return 0;
}
二、输出结果:
三、结论
由于out()函数是虚函数,因此在主函数main()中调用时,发生了动态绑定:尽管是父类的指针,但输出的却是子类对象,所以输出的是Derived::out()。动态绑定的结果是,父类指针调用了子类的实现,这就是多态。而对于in()函数,由于没有virtual修饰,不会发生动态绑定,因此只是输出的父类结果Base::in()。