指向 类成员函数 指针的用法

C++在使用函数指针调用类成员函数的时候会遇到很多问题,以下是解决办法:

代码

//test.h
class CMyc{
public:
    int fun(int);
    typedef int (CMyc::*FUNPTRTYPE)(int);
    void fun2(int);
};

//test.cpp
#include <iostream>
#include "test.h"
//写在这也可以
//typedef int (CMyc::*FUNPTRTYPE)(int);

int CMyc::fun(int i) {
    std::cout << i << std::endl;
    return i;
}

void CMyc::fun2(int i) {
    //写在这也可以
    //typedef int (CMyc::*FUNPTRTYPE)(int);

    //需要显示取址,普通函数指针赋值时可以省略取址符,但是建议加上,更加明确,易读。
    FUNPTRTYPE pfn = &CMyc::fun;
    //这步很重要,可以看到,pfn不是类成员变量,但是在解指针操作后,它的函数需要this->来调用,以获得隐含的this对象。
    ( this->*(pfn) )(i);
}

int main()
{
    CMyc m_cmyc;
    m_cmyc.fun2(100);
    return 0;
}

 

posted on 2013-05-23 16:02  horane.jo  阅读(273)  评论(0编辑  收藏  举报

导航