我在一段包含一些事件处理对象的代码中遇到了这个问题。在事件处理类中,我试图通过指针调用另一个类的函数,但是它与该代码所具有的错误相同,我已经实现了该错误,只是检查了我要在其中调用的逻辑。我在这里做什么错?
#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 ==========
update
被键入为“指向类成员函数的指针FunctionPointer
。这意味着它需要FunctionPointer
在左边的一个实例->*
。但是您正在尝试取消引用this
类型为的实例UseFP
。因此会出现错误。
您需要一个实例来对其FunctionPointer
进行调用update
。我不知道您打算使用的语义是什么,但是一种获取语义的方法是向中添加一个参数Modified
:
void UseFP::Modified(FunctionPointer &fp, int m,int n)
{
(fp.*update)(m,n);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句