一般来说,函数指针的用法是比较简单的。 比如对于函数:
1
|
int innerFunc(int num);
|
可以使用:
1
2
|
int (*ptrFunc)(int);
ptrFunc = innerFunc;//或&innerFunc
|
或者为了复用:
1
2
3
|
typedef int (*FUNC)(int);
FUNC ptrFunc;
ptrFunc = innerFunc;//或&innerFunc
|
但是当你使用类成员函数指针的时候,会发现完全不是那么一回事!而我今天就杯具的遇上了。。
废话不多说,直接上代码吧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
class Foo
{
public:
string m_str;
Foo()
{
m_str = "";
}
void test(char* str,int num)
{
m_str = str;
int (Foo::*ptrFunc)(int);
ptrFunc = &Foo::innerFunc;
//(*ptrFunc)(num);
//(this->(*ptrFunc))(num);
(this->*ptrFunc)(num);
}
int innerFunc(int num)
{
cout<<num<<endl;
cout<<m_str<<endl;
}
};
int main(int argc, const char *argv[])
{
Foo foo;
foo.test("woo",100);
return 0;
}
|
注释的部分千万不要打开,也千万不要以为是一样的,如果你不听我的劝阻非要试一下,好吧,他们会分别报如下错误:
error: invalid use of `unary *' on pointer to member
和
error: expected unqualified-id before '(' token
error: invalid use of `unary *' on pointer to member
对于原因现在也没时间去钻研了,如果哪位朋友知晓麻烦告知一下,多谢~