问题
I am defining function pointer inside a class and trying to access it through an instance of the class but it shows an error.
Here is the code:
1 #include<stdio.h>
2
3 class pointer {
4 public:
5 int (pointer::*funcPtr)(int);
6 pointer() {
7 funcPtr = &pointer::check;
8 }
9
10
11 int check(int a)
12 {
13 return 0;
14 }
15
16 };
17
18 int main()
19 {
20 pointer *pt=new pointer;
21 return (pt->*funcPtr)(3);
22 }
It shows a compile time error:
checkPointer.cpp:21:15: error: ‘funcPtr’ was not declared in this scope
please help me.
Thank You in advance.
回答1:
The issue here is that funcPtr is declared inside of pt, so you need to use the name pt twice - once as the left-hand side of the pointer-to-member-selection, and once to choose the pointer class from which to select funcPtr:
(fn->*(fn->funcPtr))(3);
The reason for this is that you could potentially call the function pointed at by the funcPtr member of one instance of pointer on another instance of pointer.
Hope this helps!
回答2:
I think you meant
pt->*(pt->funcPtr)(3);
回答3:
I'm going to suggest that you follow the instructions from the C++ FAQ. Normally, that author avoids typedef
s and #define
s, but for this case he makes an exception:
#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))
…
CALL_MEMBER_FN(*pt, pt->funcPtr)(3)
P.s. Even if you don't follow those instructions, do read that page. It has loads of useful information about pointers to member functions.
来源:https://stackoverflow.com/questions/9946015/accessing-function-pointer-inside-class