我遇到了一个带有一些事件处理对象的大段代码的问题。在一个事件处理类中,我试图通过指针调用另一个类的函数但是它具有与我已经实现的这个代码相同的错误,只是检查我用来调用那里的逻辑。我在这里做错了什么?
#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 ==========
答案 0 :(得分:2)
update
被输入为“指向类FunctionPointer
的成员函数的指针。这意味着它需要FunctionPointer
左侧的->*
实例。但你是尝试使用类型为this
的{{1}}取消引用它。因此错误。
您需要UseFP
的实例才能在其上调用FunctionPointer
。我不知道你的意图是什么,但获得一个的一种方法是向update
添加一个参数:
Modified
答案 1 :(得分:1)
你不能做这样的事情。您应该将FunctionPointer
对象传递给函数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);