#include<iostream>
using namespace std;
class A{
public:
virtual void go1()
{
cout << "A go1" << endl;
}
virtual void go2()
{
cout << "A go2" << endl;
}
virtual void go3()
{
cout << "A go3" << endl;
}
};
class B:public A{
public:
void go2()
{
cout << "B go2" << endl;
}
private:
void go3()
{
cout << "B go3" << endl;
}
};
int main()
{
B b;
cout << &b << endl;
cout << *((int *)&b) << endl;
cout << (int *)*((int *)&b) << endl;
cout << (void *)*((int *)&b) << endl;
cout << "g1的地址:" << (void *)*(int *)*((int *)&b) << endl;
我们得到虚表地址后再次进行强转(int*) 这样就找到了 虚表中第一个指针 的 地址\
上面只是找到了,虚表中指针的地址,但是我们需要的是这个指针上存放的地址(go1的地址)所以再次取内容*
cout << "g2的地址:" << (void *)(*((int *)(*((int *)&b)) + 1)) << endl;
cout << "g3的地址:" << (void *)(*((int *)(*((int *)&b)) + 2)) << endl;
cout << "☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆" << endl;
cout << "------------不创建类对象也能调用类中的非静态函数------------" << endl;
cout << "----------------在外部也能调用类中私有函数------------------" << endl;
cout << "★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★" << endl;
typedef void(*P)();
for (int i = 0; i < 3; i++)
{
((P)(*((int *)(*((int *)&b)) + i)))();
}
cout << "-----------------代码简化--------------------" << endl;
P p[3];
for (int i = 0; i < 3; i++)
{
p[i] = (P)(*((int *)(*((int *)&b)) + i));
p[i]();
}
system("pause");
}