函数指针

  用了一个小时研究了一下:C++函数指针在主函数和类成员函数中的使用。

  代码如下:

// FuncPointer.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

class AClass{
public:
    bool isEven(int n){
        if(n & 1) return true;
        return false;
    }
    
    void interfaceFunc(){
        //函数指针如果要指向类的成员函数必须要和类的方法绑定&声明为类成员函数指针
        bool (AClass::*func)(int) = &AClass::isEven;
        AClass *a = new AClass();
        //cout<<(a.*func)(1)<<endl; a 不是指针对象时候的调用方式
        solveFunc(&AClass::isEven, a);//将类的成员函数地址与类实例一起传给接收函数
    }

    void solveFunc(bool (AClass::*func)(int), AClass *p){
        if((p->*func)(1)){//指针型类实例调用类成员函数指针的方式
            cout<<"solveFunc 1"<<endl;
        }
    }
};

void funcA(int n){
    cout<<"funcA :"<<n<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    //指向普通函数的函数指针
    void (*func)(int) = &funcA;
    (*func)(1);

    //指向类成员函数的函数指针
    AClass a;
    a.interfaceFunc();
    system("pause");
    return 0;
}

 

posted on 2016-10-14 21:07  暴力的轮胎  阅读(144)  评论(0编辑  收藏  举报

导航