注册 登录
编程论坛 C++教室

VC++中的一个指针调用函数的问题

风之子MIKEY 发布于 2012-10-21 14:51, 943 次点击
class Test
{
   
public:
    void (test::*fp)(void);   
    void fun()
    {
        printf("Test fun \n");
        return ;
    }
     

    void init()
    {        
        fp=fun;        
        return ;

    }
};
main()
{
  Test t;
  t.init();
  t.fp();//////这里编译出错error C2064: term does not evaluate to a function
}
我要如何才能通过指针去调用fun函数
6 回复
#2
JYIT2012-10-21 16:28
void (test::*fp)(void);   
没必要加test::
改为void (*fp)(void);   
#3
lchpersonal2012-10-21 16:33
class Test
{
   
public:
    void (test::*fp)(void);   //函数指针??? 很少有这样用的吧!  
    void fun()
    {
        printf("Test fun \n");
        return ;
    }
     

    void init()
    {        
        fp=fun;        
        return ;

    }
};
main()
{
  Test t;
  t.init();
  t.fun();//////这样直接调用不行吗??
}


如果非得用指针的话如下:
main(){
Test *t=new Test();
t->init();
t->fun();
#4
风之子MIKEY2012-10-21 16:36
不行,你去掉test::
  void init()
{
   fp=fun;不行。//error C2440: '=' : cannot convert from 'void (__thiscall test::*)(void)' to 'void (__cdecl *)(void)'
   return ;
}
#5
JYIT2012-10-21 16:43
以下是引用风之子MIKEY在2012-10-21 16:36:28的发言:

不行,你去掉test::
  void init()
{
   fp=fun;不行。//error C2440: '=' : cannot convert from 'void (__thiscall test::*)(void)' to 'void (__cdecl *)(void)'
   return ;
}
下面的当然也要相应改,改为fp=(&fun);
#6
风之子MIKEY2012-10-21 17:06
class Test
{
   
public:
    void (test::*fp)(void);   
    void fun()
    {
        printf("Test fun \n");
        return ;
    }
     

    void init()
    {        
        fp=fun;  
            
        return ;

    }
};
main()
{
  Test t;
  t.init();
  t.fp();//////这里编译出错error C2064: term does not evaluate to a function
  改为:(t.*t.fp)();就可以啦。
}
找了很久才找到。
#7
rjsp2012-10-22 08:17
我不知道你想干什么,我只把你错误的地方改正过来
#include <cstdio>

class Test
{
public:
    void (Test::*fp)(void);
    void fun()
    {
        printf("Test fun \n");
        return;
    }
    void init()
    {        
        fp = &Test::fun;
        return;
    }
};
int main()
{
    Test t;
    t.init();
    (t.*t.fp)();

    return 0;
}
1