虚函数的静态绑定和动态绑定

#include <iostream>

using namespace std;

class A
{
public:
 A()
 {
  cout << "A()::this is "  << *(( unsigned int * )this) << endl;
  clear();
  cout << "A()::after clear this is "  << *(( unsigned int * )this) << endl;
 }
 virtual ~A()
 {
  
 }
 void clear()
 {
  memset( this, 0, sizeof( *this ) );
 }
 
 virtual void func()
 {
  cout << "func"  << endl;
 }
 
 void check()
 {
  cout << __FUNCTION__   << endl;
 }

 

   void doSth()

    {

           func(); 

    }
 
};

class B : public A
{

public:
 B()
 {
  cout << "B:this is "  << *(( unsigned int * )this) << endl;
 }
 
 virtual void func()
 {
  cout << "func in B"  << endl;
 }
 
};

class C
{
};

 

void func( char (&p) [ 10 ] )
{
 cout << "sizeof(p) is " << sizeof ( p )  << endl; // 输出为10
}
int main()
{
 char p[10];
 func( p );//
 
 A a;
 B b;
 cout << "sizeof(a) is " << sizeof( a ) << endl; // 4 个字节
 cout << "sizeof(b) is " << sizeof( b ) << endl; // 4个字节
 cout << "sizeof(c) is " << sizeof( C ) << endl; // 1个字节
 a.func(); // 可以正常执行   静态绑定函数地址
 b.func(); // 可以正常执行   静态绑定函数地址
 
 A * pA = &a;
 cout << "pA is "  << *(( unsigned int * )pA) << endl; // 0
 B * pB = &b;
 cout << "pB is "  << *(( unsigned int * )pB) << endl; // 134516552
 A * pAB = &b;
 cout << "pAB is "  << *(( unsigned int * )pAB) << endl; //134516552
 pA->check();// 这里可以正常运行
 //pA->func(); 为什么这里会引发段错误?  动态绑定,通过this指针读取虚函数表中的函数地址时coredump
 pB->func(); // 这里可以正常执行
 pAB->func(); // 这里也可以正常执行
 
 

// 如果 clear 函数实现为空,没有设置为0

 

   B b;

    b.doSth(); // 这里调用的是B::func 而不是A的func!!!!!!!!!!


 return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值