IT技术博客大学习 共学习 共进步

关于类成员函数指针的正确写法

Vimer 2010-10-10 00:57:53 浏览 2,604 次

一般来说,函数指针的用法是比较简单的。 比如对于函数:

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

对于原因现在也没时间去钻研了,如果哪位朋友知晓麻烦告知一下,多谢~

建议继续学习

  1. Linus:利用二级指针删除单向链表 (阅读 13,065)
  2. C语言结构体里的成员数组和指针 (阅读 6,083)
  3. 通过引用计数解决野指针的问题(C&C++) (阅读 4,863)
  4. C 语言中统一的函数指针 (阅读 4,187)
  5. cpp智能指针的简单实现 (阅读 4,083)
  6. 重构发现:指针操作问题 (阅读 3,485)
  7. 空指针的解引用 (阅读 3,223)
  8. 一起空指针引发的程序问题的排查过程 (阅读 2,904)