zoukankan      html  css  js  c++  java
  • C++ 获取类成员函数地址方法 浅析

    C语言中可以用函数地址直接调用函数:

    1.  
      void print ()
    2.  
      {
    3.  
      printf ("function print");
    4.  
      }
    5.  
      typdef void (*fun)();
    6.  
      fun f = print;
    7.  
      f();

    C++中类非静态成员函数必须通过实例去调用,C++中类成员函数调用:

    1.  
      class test
    2.  
      {
    3.  
      public:
    4.  
      void print ()
    5.  
      {
    6.  
      printf ("function print");
    7.  
      }
    8.  
      };

    我们同样可以通过定义函数指针来调用如下:

    1.  
      typedef void (test::*fun)();
    2.  
      fun f = &test::print;
    3.  
      test t;
    4.  
      (t.*f)();

    如果我们想取函数地址怎么办,直接强转会报错

    unsigned int a = reinterpret_cast<unsigned int>(f);//编译错误
    

    http://bbs.pediy.com/showthread.php?t=47835

    这里给出了答案.

    
    
    1.  
      char buf [32] = {0};
    2.  
      sprintf(buf , "%u", f);
    3.  
      int a = atoi( buf);

    其实我们知道类成员函数只是函数第一个参数是this指针,但是this指针不是通过普通函数参数压栈方式,而是放进ecx中。

  • 相关阅读:
    delphi实现FTP下载
    delphi中ClientDataSet的隐含功能
    删除注册的ODBC
    ZOJ 1041 Transmitters
    POJ 3232 Accelerator
    POJ 3460 Booksort
    UVa 11552 Fewest Flops
    SOJ 8064 Whack the Groundhog
    BNU OJ 29355 手速为王
    POJ 3322 Bloxorz I
  • 原文地址:https://www.cnblogs.com/lidabo/p/9374134.html
Copyright © 2011-2022 走看看