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

标签 c++

我试图拥有一个 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/

相关文章:

c++ - Cython 调用 MKL 通过 vdMul 在元素乘法上崩溃

c++ - Unicode - 通常在 C++ 中使用它

c++ - Windows Hook 和 DLL 加载

c++ - WaitForSingleObject - 等待队列的线程吗?

c++ - OpenGL es 2.0 三角形高斯模糊

c++ - 将 float 组作为 3D 纹理传递给 GLSL 片段着色器

c++ - if 表达式中的操作顺序是否改变?

c++ - 从 Fortran 调用 C++(链接问题?)

c++ - std::set 和 std::map 有什么区别

c++ - 错误 :unable to match function definition to an existing declaration