直接用函数作为某个类的回调函数没有问题,但是用类方法作为回调函数就有问题。下面是测试代码,#include "stdafx.h"
#include <iostream.h>
#include <stdlib.h>class callback
{
typedef void (*IntF)(int);
public:
callback(IntF f = NULL) : _f(f), foo(NULL)
{
}
void run(int i)
{
if(_f) _f(i);
if(foo) foo(i);
}
private:
IntF _f;
};class foo
{
public:
void foo1(int i)
{
cout << "i = " << i << endl;
}
void foo2(int i)
{
cout << "i*i = " << i*i << endl;
}
};
void foo1(int i)
{
cout << "i = " << i << endl;
}
void foo2(int i)
{
cout << "i*i = " << i*i << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
/*
//这样回调不可以
foo f;
callback cb1(f.foo1); // or (foo::foo1)
cb1.run(10);
callback cb2(foo::foo2); // or (foo::foo2)
cb2.run(20);
*/
callback cb3(foo1);
cb3.run(10);
callback cb4(foo2);
cb4.run(20); system("pause");
return 0;
}在BCB中可以用 __closure 解决这个问题,如把回调的声明改为
typedef void (__closure *IntF)(int);
即可,BCB中,用这种方式做事件,以便任意挂接事件处理函数。VC中,如何解决?
#include <iostream.h>
#include <stdlib.h>class callback
{
typedef void (*IntF)(int);
public:
callback(IntF f = NULL) : _f(f), foo(NULL)
{
}
void run(int i)
{
if(_f) _f(i);
if(foo) foo(i);
}
private:
IntF _f;
};class foo
{
public:
void foo1(int i)
{
cout << "i = " << i << endl;
}
void foo2(int i)
{
cout << "i*i = " << i*i << endl;
}
};
void foo1(int i)
{
cout << "i = " << i << endl;
}
void foo2(int i)
{
cout << "i*i = " << i*i << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
/*
//这样回调不可以
foo f;
callback cb1(f.foo1); // or (foo::foo1)
cb1.run(10);
callback cb2(foo::foo2); // or (foo::foo2)
cb2.run(20);
*/
callback cb3(foo1);
cb3.run(10);
callback cb4(foo2);
cb4.run(20); system("pause");
return 0;
}在BCB中可以用 __closure 解决这个问题,如把回调的声明改为
typedef void (__closure *IntF)(int);
即可,BCB中,用这种方式做事件,以便任意挂接事件处理函数。VC中,如何解决?
解决方案 »
- 新手求助, message in tab control->staic control->other control
- MFC求助
- MFC基于对话框的应用程序关闭主对话框时出错。
- VC开发中可能用到一个表,我有可能有要更新又要查询,怎么样才能不冲突?
- 请教如何定期杀死一个进程
- 高分征解SQL语言问题
- 关于Win32通用控件的TreeView节点图片的问题
- 关于在atl 控件中建立一个 IDISPATCH 回调对象的 讨论
- Win98下加载DLL失败是怎么回事?
- 如何将浏览器发过来的诸如“%E5%B2%E7%D4%E5%62”请求转为中文?
- 新来的提问,请大家多多指教:显示列表
- IE插件注册问题(只剩这么多分了)
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcsample/html/vcsameventhandlingsamples.asp