技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> 其他 --> 关于类成员函数指针的正确写法

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

浏览:1921次  出处信息

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

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:利用二级指针删除单向链表    (阅读:11140)
  2. C语言结构体里的成员数组和指针    (阅读:4590)
  3. 通过引用计数解决野指针的问题(C&C++)    (阅读:3359)
  4. C 语言中统一的函数指针    (阅读:2971)
  5. cpp智能指针的简单实现    (阅读:2930)
  6. 重构发现:指针操作问题    (阅读:2276)
  7. 空指针的解引用    (阅读:2157)
  8. 一起空指针引发的程序问题的排查过程    (阅读:1897)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1