LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1049|回复: 5

如何得到成员函数的地址?

[复制链接]
发表于 2006-4-30 15:03:00 | 显示全部楼层 |阅读模式
class A{ public:int f();};

int main(){
A a;
int (*p)()=&(a.f);///// error?  iso c++ forbins?

请问如何得到成员函数的地址?
不一定要用指针指向成员函数
我只要得到该成员函数的32位入口地址就好.
不要使用c++的高级特性
发表于 2006-4-30 18:52:36 | 显示全部楼层
不如先说说为什么要这么做
回复 支持 反对

使用道具 举报

发表于 2006-4-30 21:59:12 | 显示全部楼层
int (*p)()=&(a.f);

这个是错误的写法................
回复 支持 反对

使用道具 举报

发表于 2006-4-30 22:20:56 | 显示全部楼层
  1. class A
  2. {
  3. public:
  4.   static int f();
  5. };
  6. int A::f()
  7. {
  8.   return 0;
  9. }
  10. typedef int (*F)();
  11. int main()
  12. {
  13.   A a;
  14.   F f = a.f;
  15. }
复制代码
回复 支持 反对

使用道具 举报

发表于 2006-5-1 09:43:24 | 显示全部楼层
typedef int (A::*F)();
回复 支持 反对

使用道具 举报

发表于 2006-5-1 14:04:58 | 显示全部楼层
可能的用法:
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class A {
  5. public:
  6.     string m_var;
  7.     A() {
  8.         m_var = "Thins is a member variable.";
  9.     }
  10.     int member_f() {
  11.         cout << "This is a member function()." << endl;
  12.         return 0;
  13.     }
  14.     static int static_f() {
  15.         cout << "This is a static function()." << endl;
  16.         return 0;
  17.     }
  18. };
  19. int main() {
  20.     A a;
  21.     A *p2a = &a;
  22.    
  23.     int (*p_to_static_f)() = A::static_f;
  24.     string A::*p_to_member_var = &A::m_var;
  25.     int (A::*p_to_member_f)() = &A::member_f;
  26.     p_to_static_f(); //static fucntion
  27.     cout << (a.*p_to_member_var).c_str() << endl;
  28.     (a.*p_to_member_f)();
  29.     cout << (p2a->*p_to_member_var).c_str() << endl;
  30.     (p2a->*p_to_member_f)();   
  31.     return 0;
  32. }
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表