一 成员指针
成员指针前面的qualifier确定了用什么类型的对象或对象操作,比如
int T::* // 用T类型对象或T*操作
// 用T2类型对象操作或T2*操作
void (T1::T2::*)()
void (T2::*)()
成员指针分类
-
数据成员指针:
8个字节, 为在对象中的偏移量。 -
函数成员指针:
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