【问题标题】:Can we create an Adapter patterns using function pointers?我们可以使用函数指针创建适配器模式吗?
【发布时间】: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: '&' : 对绑定成员函数表达式的非法操作

连同之前的错误消息。这可能意味着&amp; 运算符无法从pAdOne-&gt;Responce1 创建函数指针。

这是否意味着我们可以t have a function pointer in someClassAwhich could point to a non-static function present in anotherClassB`?

【问题讨论】:

标签: c++


【解决方案1】:

在分配成员函数指针时,您为其分配成员函数指针,如AdapteeTwo::Responce2

所以它应该是例如

fnptrTwo =  &AdapteeTwo::Responce2;

你在调用成员函数指针时使用对象:

(pAdTwo->*fnptrTwo)()

最后一条语句调用pAdTwo对象中fnptrTwo指向的函数,所以pAdTwo在被调用的成员函数中将是this

【讨论】:

  • 我尝试了以下相同的方法:fnptrOne = &(AdapteeOne::Responce1); fnptrTwo = &(AdapteeTwo::Responce2);但收到错误消息:“错误 C2064:术语不计算为采用 0 个参数的函数。错误语句非常令人困惑。请评论。”。我可以看到错误来了,因为这两个函数都是成员函数,所以隐式参数“this”作为参数传递。
  • @Anitesh 我不是说你如何声明函数指针,而是你如何分配和调用它们,你必须改变。
  • 请看一下我的第一次尝试代码:class Adapter { public: int (AdapteeOne::*fnptrOne)(void); int (AdapteeTwo::*fnptrTwo)(void); Adapter(AdapteeOne* adone) { fnptrOne = &amp;(AdapteeOne::Responce1); this-&gt;*fnptrOne(); } Adapter(AdapteeTwo adtwo) { fnptrTwo = &amp;(AdapteeTwo::Responce2); } }; void main() { Adapter* adpter = new Adapter(new AdapteeOne()); (pAdTwo-&gt;*fnptrTwo)(); } 上面的代码不起作用并给出错误 C2064,如上所述。我是不是误会你说的了?
  • @Anitesh 但是你没有在main 函数中声明任何变量pAdTwofnptrTwo,所以是的,这会给你编译错误。同样在AdapteeOne 的构造函数中,您忘记了对象周围的括号(并且它不是this,您应该调用函数,而是adone)和函数指针,这也会导致错误。
  • @Anitesh 我真的建议你阅读我对std::functionstd::bind 的评论。如果您开始使用它们,最终会让您的生活更轻松。
猜你喜欢
  • 2011-04-05
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 2019-09-08
  • 1970-01-01
  • 2021-10-17
相关资源
最近更新 更多