C++コールバック関数

1961 ワード

C++関数のコールバック
C++関数のコールバックを理解する前に、まずtypedefの使用を理解しなければならない.typedefの使用は、複雑な変数に簡単で覚えやすい名前を与えることであり、それ自体は新しいタイプを作成せず、複雑なタイプ宣言を簡略化する.
1.複雑な変数に簡単で覚えやすい名前を与える.
typedef char *pChar;//本質はchar*mystrを表す.pChar mystr;
2.複雑なタイプ宣言を簡略化する.
//定義関数PrintHello void A::PrintHello(int);//関数ポインタptrFuncを宣言します.typedef void (*ptrFunc)(int);
void A::PrintHello(int i){//定義関数ポインタ変数ptrFunc ptr;ptr=&PrintHello;(*ptrFunc)(*ptrFunc)(*ptrFunc)}
本題に入ります:コールバックの実質は他の人が関数を実行する時、パラメータを伝達する方式を通じて、あなたの実現した関数を呼び出します;
#pragma once
#include 

typedef std::function mCallback;
typedef bool (*pFun)(int, int);


// 1.     
// 2.     
class TestClass
{
public:
	int ClassMember(int a) { return a; }
	static int StaticMember(int a) { return a; }
};

//   
class funtor
{
public:
	void operator()(int a) {

	}
};
class typeOf
{
public:
	
	typeOf();
	~typeOf();
	
	bool pSort(int age1, int age2, pFun p);
	
	void pStar();
	void mMain();
};

ヘッダファイルは、後の使用に便利ないくつかのクラスを宣言します.
//ポインタコールバック
//     pFun  
bool typeOf::pSort(int age1, int age2, pFun p) {
	if (age1>age2)
	{
		return p(age1,age2);
	}
	return false;
}

bool CompareAge(int cAge, int cAge2) {

	return cAge > cAge2;
}


void typeOf::pStar() {
    //      
	pFun pStrs= CompareAge;
	bool flag=pSort(2, 3, pStrs);
	
}


//    ;
void f1(char* s);
void f2(char* s);
typedef void (*Fp)(char*);

void f1(char* s) {
	std::cout << 1;
}

void f2(char* s) {
	std::cout << 1;
}


void ToFunc() {
	Fp f[] = {f1,f2};
	//       
	f[0];
}


typedef int(*mStr)(bool);

int mTest(bool flag) {
	std::cout << 22;
	return 2;
}

//std::function 


void typeOf::mMain() {
	mStr mMa = mTest;
	mMa(5);
	//      
	mCallback mCall;
	mCall(5);
	//     
	funtor fun;
	mCallback mFun;
	fun(7);
	//        
	TestClass tc;
	mCallback mTc;
	mTc = std::bind(&TestClass::ClassMember, tc, std::placeholders::_1);
	mTc(5);
}