zoukankan      html  css  js  c++  java
  • 【C++ 基础 11】 函数指针总结

    在家学习的效率真是惨不忍睹。。

    ===========================

    1 指针函数

    int* f(int a, int b);
    返回一个指向int类型的指针。

    2 函数指针

    2.1 声明

    返回类型 (*函数名)(参数列表);

    2.2 示例

    int max(int a, int b) {  return a > b ? a : b;  }  
    int min(int a, int b) {  return a < b ? a : b;  }  
      
    int (*f)(int, int); // 声明函数指针f,指向返回值类型为int,有两个参数类型都是int的函数  
      
    void main()  
    {  
        f = max; // 函数指针f指向求最大值的函数max  
        int c = (*f)(1, 2);  
        printf("The max value is %d 
    ", c);  // 2
      
        f = min; // 函数指针f指向求最小值的函数min  
        c = (*f)(1, 2);  
        printf("The min value is %d 
    ", c);  // 1
    
        return ;  
    }

    3 typedef简化函数指针

    一般我们会经常使用typedef来简化函数指针的调用。

    3.1 声明

    typedef 返回类型 (*函数指针类型名)(函参列表);

    typedef是定义新的类型,定义这种类型为指向某种函数的指针。

    3.2 示例

    int max(int a, int b) {  return a > b ? a : b;  }  
    int min(int a, int b) {  return a < b ? a : b;  }  
    
    //定义Func类型,Func是指向 返回int且参数为2个int的函数 的指针
    typedef int (*Func)(int,int);
    
    void main()  
    {  
    	Func pFunc = NULL; //声明变量pFunc
    	pFunc = &max;      //或者pFunc = max两种写法 
    	int c = pFunc(1,2);
    	printf("The max value is %d 
    ", c);  // 2
    	return ;  
    }  

    4 类成员函数指针

    类成员包含静态和非静态函数,静态跟对象无关。

    4.1 非静态成员函数声明

    typedef 返回类型 (类名::*函数指针类型名)(函参列表);

    4.2 静态成员函数声明(和一般函数指针一样)

    typedef 返回类型 (*函数指针类型名)(函参列表);

    4.3 示例

    class A{
    public:
    	int max(int a, int b) {  return a > b ? a : b;  }  
    	static int min(int a, int b) {  return a < b ? a : b;  }  
    };
    
    typedef int (A::*ClassFunc)(int,int);//类成员函数指针定义
    typedef int (*StaticFunc)(int,int);  //静态函数指针定义(和普通的函数指针相同)
    
    void main()  
    {  
    	/*
    	 *  类成员函数指针
    	 */
    	ClassFunc pClassFunc = &A::max; //类成员函数必须加&符号,否则报错
    	//写法1
    	A a;
    	int c = (a.*pClassFunc)(3,6);
    	cout<<c<<endl; //6
    	//写法2
    	A* pA = &a;      
    	c = (pA->*pClassFunc)(3,6);
    	cout<<c<<endl; //6
    
    	/*
    	 *  静态成员函数指针
    	 */
    	StaticFunc pStaticFucn = &A::min; //可加&,可不加
    	c = pStaticFucn(3,6);
    	cout<<c<<endl; //3
    }  



  • 相关阅读:
    Android调用第三方so
    九度oj题目1518:反转链表
    九度oj题目1014:排名
    九度oj题目1012:畅通工程
    九度oj题目1027:欧拉回路
    九度oj题目1348:数组中的逆序对
    九度oj题目1521:二叉树的镜像
    九度oj题目1385:重建二叉树
    poj 1577 Falling Leaves
    poj 1321 棋盘问题
  • 原文地址:https://www.cnblogs.com/fzll/p/3954578.html
Copyright © 2011-2022 走看看