【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
}