class Class1 { public: virtual void f() { cout << "Function f() in Class1 "; } void g() { cout << "Function g() in Class1 "; } }; class Class2 { public: virtual void f() { cout << "Function f() in Class2 "; } void g() { cout << "Function g() in Class2 "; } }; class Class3 { virtual void h() { cout << "Function h() in Class3 "; } }; int main() { Class1 object1, * p; Class2 object2; Class3 object3; p = &object1; p->f(); p->g(); p = (Class1*)& object2; p->f(); p->g(); p = (Class1*)& object3; //p->f(); p->g(); }
输出:
Function f() in Class1
Function g() in Class1
Function f() in Class2
Function g() in Class1
Function g() in Class1
类型指针是通过地址访问的:数据成员分静态绑定和动态绑定,比如g函数始终是类型Class1的成员,但f()函数因为是虚函数绑定会延迟到运行时,因此当指针P指向Class2时候调用f()会动态分配执行内存Class2 的f()函数,有点类似于接口、抽象类继承后实现的多态性 原理一致。