Accessing function pointer inside class

2019-05-06 22:53发布

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.

3条回答
叛逆
2楼-- · 2019-05-06 23:36

I think you meant

pt->*(pt->funcPtr)(3);
查看更多
Emotional °昔
3楼-- · 2019-05-06 23:43

I'm going to suggest that you follow the instructions from the C++ FAQ. Normally, that author avoids typedefs and #defines, 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.

查看更多
再贱就再见
4楼-- · 2019-05-06 23:45

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!

查看更多
登录 后发表回答