gpt4 book ai didi

c++ - 我们可以使用函数指针创建适配器模式吗?

转载 作者:行者123 更新时间:2023-11-28 07:20:48 26 4
gpt4 key购买 nike

我试图拥有一个 Adapter 类,它有一个函数指针(比如 fnPtr)。并且根据不同的 Adaptee 类,fnPtr 会被赋予相应的 Adaptee 函数。以下是代码片段:

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() 函数中。我无法通过任何方式调用 Adapter 的函数指针(fnptrOnefnptrTwo`)。我得到:

error C2276: '&' : illegal operation on bound member function expression

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

这是否意味着我们不能某些ClassA中的函数指针可以指向另一个ClassB 中存在的非静态函数?

最佳答案

当分配一个成员函数指针时,您为它分配了成员函数指针,如AdapteeTwo::Responce2

所以它应该是例如

fnptrTwo =  &AdapteeTwo::Responce2;

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

(pAdTwo->*fnptrTwo)()

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

关于c++ - 我们可以使用函数指针创建适配器模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19492471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com