1

我有一大段代码有这个问题,其中有一些事件处理对象。在一个事件处理类中,我试图通过指针调用另一个类的函数,但它与这个代码有相同的错误,我已经实现了这个代码来检查我用来在那里调用的逻辑。我在这里做错了什么?

#include <iostream>
using namespace std;
class FunctionPointer;
class UseFP
{
public:
    UseFP(void){}
    ~UseFP(void){}

    void Modified(int m,int n);
    void (FunctionPointer::*update)(int,int);

};

void UseFP::Modified(int m,int n)
    {
            //(this->*update)(m,n);// call by fp if I uncomment it it gives error.
    }

class FunctionPointer
{
    int a,b;
    UseFP * obj;
public:
    FunctionPointer(void);

    ~FunctionPointer(void);

    void updateData(int m, int n)
    {
        a = m;
        b = n;
        cout<<"\n\nUpdated: a "<<a<<", b "<<b<<endl;
    }

    void Input()
    {
        int m, n;
        cout<<"\nEnter new data: ";
        cin>>m>>n;
        obj->Modified(m,n);
    }
    };

void main()
{
    FunctionPointer obj;
    obj.Input();
}

取消注释函数调用后的错误

1>------ Build started: Project: FunctionPointer, Configuration: Debug Win32 ------
1>Compiling...
1>main.cpp
1>c:\users\volmo\desktop\functionpointer\functionpointer\functionpointer.h(14) : error C2440: 'newline' : cannot convert from 'UseFP *const ' to 'FunctionPointer *const '
1>        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>c:\users\volmo\desktop\functionpointer\functionpointer\functionpointer.h(14) : error C2647: '->*' : cannot dereference a 'void (__thiscall FunctionPointer::* )(int,int)' on a 'UseFP *const '
1>Generating Code...
1>Compiling...
1>FunctionPointer.cpp
1>c:\users\volmo\desktop\functionpointer\functionpointer\functionpointer.h(14) : error C2440: 'newline' : cannot convert from 'UseFP *const ' to 'FunctionPointer *const '
1>        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>c:\users\volmo\desktop\functionpointer\functionpointer\functionpointer.h(14) : error C2647: '->*' : cannot dereference a 'void (__thiscall FunctionPointer::* )(int,int)' on a 'UseFP *const '
1>Generating Code...
1>Build log was saved at "file://c:\Users\volmo\Desktop\FunctionPointer\FunctionPointer\Debug\BuildLog.htm"
1>FunctionPointer - 4 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
4

2 回答 2

2

update被键入为“指向 class 的成员函数的指针FunctionPointer。这意味着它需要.FunctionPointer左侧的实例->*。但是您试图取消引用它this的 type UseFP。因此出现错误。

您需要一个实例FunctionPointer来调用update它。我不知道您的预期语义是什么,但获得语义的一种方法是将参数添加到Modified

void UseFP::Modified(FunctionPointer &fp, int m,int n)
    {
            (fp.*update)(m,n);
    }
于 2013-09-04T06:48:38.653 回答
1

你不能做这样的事情。您应该将FunctionPointerobject 传递给 function Modified,或存储为类变量。

void UseFP::Modified(FunctionPointer* p, int m,int n)
    {
       (p->*update)(m,n);// call by fp if I uncomment it it gives error.
    }

并称它为

obj->Modified(this,m,n);
于 2013-09-04T06:46:25.743 回答