通过基类的指针可以实现动态绑定,同样,通过基类的引用,也可以实现动态绑定。
#include "iostream"
#include "stdlib.h"
using namespace std;
class emptyA
{
public:
emptyA(int a){v=a;}
void fun(){cout<<"emptyA\n";}
virtual void vfun(){cout<<"base"<< v<<endl;}
int v;
};
class emptyB:public emptyA
{
public:
emptyB(int a):emptyA(a){}
virtual int fun1(){}
void fun2(){ emptyA::fun();}
void vfun(){ cout<< "inherit :"<< v<< endl;}
};
int main(int argc , char** argv)
{
emptyA a(1);
emptyB b(2);
emptyA *p = &a;
p->vfun(); // 通过基类指针调用虚函数
p = &b;
p->vfun();
emptyA &r=b; // 通过引用调用虚函数
r.vfun();
r=a; // 引用的关系没有变化,将a对象赋值为r,及将a赋值为b
r.vfun(); // output: inherit :1
return 0;
}