zoukankan      html  css  js  c++  java
  • 108.虚函数表原理(获取虚函数)

     1 //#include <iostream>
     2 //using namespace std;
     3 //
     4 //
     5 //void main()
     6 //{
     7 //    cin.get();
     8 //}
     9 
    10 #define _CRT_SECURE_NO_WARNINGS
    11 #include <iostream>
    12 using namespace std;
    13 
    14 class father
    15 {
    16 public:
    17     //虚函数表存放在首地址
    18     virtual void go1()
    19     {
    20         cout << "go1" << endl;
    21     }
    22     virtual void go2()
    23     {
    24         cout << "go2" << endl;
    25     }
    26     virtual void go3()
    27     {
    28         cout << "go3" << endl;
    29     }
    30 };
    31 
    32 class son :public father
    33 {
    34 public:
    35 
    36     void go1()
    37     {
    38         cout << "son go1" << endl;
    39     }
    40 
    41     void go2()
    42     {
    43         cout << "son go2" << endl;
    44     }
    45 
    46     void go3()
    47     {
    48         cout << "son go3" << endl;
    49     }
    50 };
    51 
    52 void main()
    53 {
    54     father *p = new son;
    55     cout << sizeof(*p) << endl;
    56     //对象的地址
    57     cout << (void*)p << endl;
    58     //虚函数表的地址
    59     cout << (void*)(*((int *)p)) << endl;
    60     //第一个元素的地址 类型转换->读内存->类型转换使得步长为4个字节
    61     cout << (void*)(   ((int *)*((int *)p) +0)      ) << endl;
    62     
    63     //取出函数表中的函数
    64 
    65     auto fun1 = (void*)(   *((int *)*((int *)p) + 0)   );
    66     auto fun2 = (void*)(   *((int *)*((int *)p) + 1)   );
    67     auto fun3 = (void*)(   *((int *)*((int *)p) + 2)   );
    68 
    69     typedef void(*P)();
    70 
    71     //函数指针数组
    72     P pfun[3];
    73     pfun[0] = (P)fun1;
    74     pfun[1] = (P)fun2;
    75     pfun[2] = (P)fun3;
    76 
    77     for (int i = 0; i < 3; i++)
    78     {
    79         pfun[i]();
    80     }
    81     cin.get();
    82 }
  • 相关阅读:
    BUUCTF--Youngter-drive
    BUUCTF--CrackRTF
    FireShell CTF 2020 Re Simple Encryption
    2020 美国大学生数学建模论文翻译(week 2)
    仿射密码
    乘法逆元
    RC4加密与解密
    2020 BJDCTF Re encode
    2020美国大学生数学建模(MCM/ICM)A题数据及参考资料
    路由器, 美团笔试题, 差分
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8604595.html
Copyright © 2011-2022 走看看