类访问的动态绑定

/*

**test28.cpp : Defines the entry point for the console application.

**系统winXP SP3 32位.

**类访问的动态绑定

*/


#include "stdafx.h"

#include "iostream.h"


class A{

public:

virtual void f(){

cout<<"A::fA1()"<

};

};


class B:public A{

public:

void f(){

cout<<"B::fB1()"<

};

};


class C:public B{

public:

void f(){

cout<<"C::fC1()"<

};


};


class D{

public:

virtual ~ D(){}

virtual void output(){};

};


class E:public D{

public:

E():eNum(0){}

virtual ~E(){}

virtual void output(int){

cout<<"E::fE1(int)"<

}


virtual void output(){

cout<<"E::fE1()"<

}


private:

int eNum;

};



int main(int argc, char* argv[])

{

A* pa = NULL;

A a;

B b;

C c;

a.f(); //fA1()

b.f(); //fB1()

c.f(); //fC1()


pa = &a;

pa->f(); //fA1()


pa = &b;

pa->f(); //fB1(),程序会根据动态绑定来确定具体调用的函数,若上面的父类A中函数不为virtual型,则此处调用的是fA1()


int iNum = 0;

D d;

D* pd= &d;

//pd->output(iNum); //错误

pd->output(); //空白输出


E* pe = new E;

pe->output(); //E::fE1()

pe->output(iNum); //E::fE1(int)



return 0;

}


Tips1:派生类的函数或成员变量会遮蔽掉父类中的同名函数或成员变量。

你可能感兴趣的:(类访问的动态绑定)