成员指针和动态绑定

一 成员指针

成员指针前面的qualifier确定了用什么类型的对象或对象操作,比如

int T::*  // 用T类型对象或T*操作

// 用T2类型对象操作或T2*操作
void (T1::T2::*)() 
void (T2::*)()

成员指针分类

  1. 数据成员指针:
    8个字节, 为在对象中的偏移量。

  2. 函数成员指针:
    16个字节, 高八字节为this指针的偏移.类型转换时会赋值,假如由void (T1::)()转换为 void (T2::)(),那么偏移为:
    T1对象的地址 - T2对象的地址(T1对象为T2对象的子对象, 或者T2对象为T1对象的子对象)
    如果T1是T2的基类, 那么可以隐式转换, 否则, 用static_cast转换.

    低八字节根据作用不同分为下面两种:
    i) 普通成员函数指针: 函数的地址,为偶地址
    ii) 虚函数成员指针: 虚函数在虚函数表里的偏移按位或0x1。
    可以用最低位是否为1区分普通成员函数指针和虚函数成员指针.

    In C++, pointer to member functions (PMFs) are implemented using a wide pointer of sorts to handle all the possible call mechanisms; the PMF needs to store information about how to adjust the ‘this’ pointer, and if the function pointed to is virtual, where to find the vtable, and where in the vtable to look for the member function. – gcc手册

二 虚函数表

// pointer_to_member.h

// gcc13.2.1编译 -m64  

#ifndef __PONINTER_TO_MEMBER_H
#define __PONINTER_TO_MEMBER_H

struct A
{
   
    virtual void afunc1() {
   }
    virtual void afunc2() {
   }
    virtual ~A() {
   }
};
struct B
{
   
    void bfunc() {
   }
    virtual void bfunc1() {
   }
    virtual void bfunc2() {
   }
    virtual ~B() {
   }
};
struct C {
    long c1; char c2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值