1、多态的关键在于通过基类指针或引用调用一个虚函数时,编译时不确定调用的是基类还是派生类的函数,运行时才能确定,这叫动态联编。
例子:
#include <iostream>
using namespace std;
class Base
{
public:
int i;
virtual void Print(){ cout << "dd"; }
};
class Derived :public Base
{
public:
int i;
virtual void Print(){ cout << "dd"; }
};
int main()
{
cout << sizeof(Base) << "," << sizeof(Derived);
return 0;
}
输出:8,12
2、多态实现的关键—虚函数表:
每一个有虚函数的类(或者虚函数类的派生类)都有一个虚函数表,该类的任何对象中都放着虚函数表的指针。虚函数表中列出了该类的虚函数地址。