父类函数调用虚函数

来源:互联网 发布:淘宝联盟丢单 编辑:程序博客网 时间:2024/06/17 01:24

http://blog.sina.com.cn/s/blog_466496f30100xp2l.html

rules:

1.如果在父类函数中调用父类的虚函数,且该虚函数在子类中被改写了,那么在把子类指针/引用交给父类指针/引用的时候,在调用父类中的函数,该函数内的虚函数实际上是子类中改写过的。

#include<stdio.h>
class base
{
 public:
void a()
{
printf("base a\n");
b(1);
};
virtual void b(int x)
{
printf("base b %d \n",x);
};
};

class ext:public base
{
 virtual void b(int x)
{
printf("ext b %d \n",x);
};

};

int main()
{
 ext ext_i;
 base base_i;
 base*  base_p;
 base&  base_r=ext_i;
 base_p=&ext_i;
 base_p->a();
 base_r.a();
 base_i.a();
 return(0);
 
}

result:

[zhliu@sdcsn05 ~]$ test43
base a
ext b 1
base a
ext b 1
base a
base b 1


0 0
原创粉丝点击