C++成员函数指针 C++委托
我想用 C++实现如 C#的委托和事件! 就是这样的:TestB 里面可以包含 TestA的实例。而TestA 不可以包含TestB的实例。当TestA中发生某一件事情以后(如程序中 i 是 10的整数倍时)会把TestA中的某值(TestA循环中的i)作为参数传递给TestB中的某方法(TestB中的CalledByTestA)而调用该方法。因为在TestA中不能实例化TestA 而 CalledByTestA非静态。只好用成员函数指针&TestB::CalledByTestA 于是我想在TestA中定义一个成员函数指针 void (TestA::*p)(EventArgs *)指向TestB::CalledByTestA, 但是编译时错误
d:\MyWorkSpace\Test\test.cpp(48): error C2440: “初始化” : 无法从“void (__thiscall TestB::* )(EventArgs *)”转换为“void (__thiscall TestA::* )(EventArgs *)”
我该怎么办? 程序是我在这里写的,可能有错误。但是思想就是那样的!
#include "iostream"
using namespace std;
class EventArgs
{
public:
int Para;
EventArgs(int parameter)
{
Para = parameter;
}
};
class TestA
{
public:
TestA(){};
Start()
{
for(int i = 0; i < 10000; i ++)
{
if(i % 10 == 0)
{
EventArgs *e = new EventArgs(i);
void (TestA::*p)(EventArgs *) = &TestB::CalledByTestA
//TestB::CalledByTestA(e);// CalledByTestA is not static, so can't be used by that way.and class TestB'instance can't be created.
delete e;
}
}
}
};
class TestB
{
public:
TestB(){};
CalledByTestA(EventArgs &e)
{
cout << e.parameter << endl;
}
};
int main()
{
TestA * testA = new TestA();
testA->Start();
delete testA;
}
[解决办法]
对于类的成员函数方法,不但需要指针,还需要类,所以你可以这么做:
void (TestB::*funcPtr)( EventArgs * ) = &TestB::CalledByTestA;TestB b;(b.*funcPtr)(e) ;
[解决办法]
code project的源码都是可以下载的啊。你注册一下就可以看到下载链接。