【发布时间】:2013-10-21 10:48:59
【问题描述】:
我试图有一个适配器类,它有一个函数指针(比如fnPtr)。并且根据不同的Adaptee类,fnPtr将被分配相应的Adaptee的功能。
以下是代码sn-p:
class AdapteeOne
{
public:
int Responce1()
{
cout<<"Respose from One."<<endl;
return 1;
}
};
class AdapteeTwo
{
public:
int Responce2()
{
cout<<"Respose from Two."<<endl;
return 2;
}
};
class Adapter
{
public:
int (AdapteeOne::*fnptrOne)();
int (AdapteeTwo::*fnptrTwo)();
Adapter(AdapteeOne* adone)
{
pAdOne = new AdapteeOne();
fnptrOne = &(pAdOne->Responce1);
}
Adapter(AdapteeTwo adtwo)
{
pAdTwo = new AdapteeTwo();
fnptrTwo = &(pAdTwo->Responce2);
}
void AdapterExecute()
{
fnptrOne();
}
private:
AdapteeOne* pAdOne;
AdapteeTwo* pAdTwo;
};
void main()
{
Adapter* adpter = new Adapter(new AdapteeOne());
adpter->AdapterExecute();
}
现在我面临的问题是main() 函数。我没有办法打电话给 Adapters function pointers (fnptrOneandfnptrTwo`)。
我得到:
error C2276: '&' : 对绑定成员函数表达式的非法操作
连同之前的错误消息。这可能意味着& 运算符无法从pAdOne->Responce1 创建函数指针。
这是否意味着我们可以t have a function pointer in someClassAwhich could point to a non-static function present in anotherClassB`?
【问题讨论】:
-
作为提示,您可能想了解
std::function和std::bind。我在this old answer of mine 中解释了如何使用它们。 -
你也可以阅读this。
标签: c++