#include <stdio.h>
struct Person {
int age;
int height;
Person();
void func1();
virtual void func2();
virtual void func3();
};
Person::Person()
{
this->age = 0;
this->height = 0;
}
void Person::func1()
{
printf("func1\n");
}
void Person::func2()
{
printf("func2\n");
}
void Person::func3()
{
printf("func3\n");
}
void test()
{
Person per;
printf("sizeof(Person): %lu\n", sizeof(Person));
printf("add of per: %p\n", &per);
printf("add of age: %p\n", &(per.age));
printf("add of height: %p\n", &(per.height));
// printf("add of func2: %p\n", &(per.Person));
// printf("add of func2: %p\n", &(per.func1));
// printf("add of func2: %p\n", &(per.func2));
// printf("add of func3: %p\n", &(per.func3));
per.func2();
per.func3();
Person *pper = &per;
typedef void (*pFun)(void);
pFun pfun2 = (pFun)(*((long int *)(*(long int *)(&per)) + 0));
printf("add of pfun2: %p\n", pfun2);
pfun2();
pFun pfun3 = (pFun)(*((long int *)(*(long int *)(&per)) + 1));
printf("add of pfun3: %p\n", pfun3);
pfun3();
}
int main(int argc, char **agrv)
{
test();
}
1. 构造函数和普通成员函数不占大小,应该是存放在“全局函数表”,只不过编译器编译时不让直接使用,必须通过对象或对象指针访问
2. virtual函数会在类(结构体)中增加一个函数指针地址,无论多少个virutal,只增加一个地址,并且位于对象的首地址,这个地址是虚函数表首地址