c++

函数指针

c++

Posted by YiMiTuMi on October 30, 2023

函数指针

一个成员函数指针包括成员函数的返回类型,后随::操作符类名,指针名和函数的参数。

格式是:函数返回类型,类名,::操作符,指针星号,指针名,函数参数。 

外部函数指针

例子:

int FunctionPointer(int a, int b)
{
	return a + b;
}

int main()
{
	//定义函数指针
	int (*pFunctionPointer) (int, int);
	pFunctionPointer = FunctionPointer;

	//调用
	int iSum = pFunctionPointer(1, 2);

	return 0;
}

成员函数指针

例子:

class CFunctionPointer
{
public:
	CFunctionPointer();
	~CFunctionPointer();


public:

	int FunctionPointer(int a, int b);
	void use();

	//定义一个函数指针
	int (CFunctionPointer::* pFunctionPointer) (int, int);
};

CFunctionPointer::CFunctionPointer()
{
	pFunctionPointer = NULL;  //初始化
}

CFunctionPointer::~CFunctionPointer()
{
}

int CFunctionPointer::FunctionPointer(int a, int b)
{
	return a + b;
}

void CFunctionPointer::use()
{
	//赋值
	pFunctionPointer = &CFunctionPointer::FunctionPointer;

	//类内调用
	(this->*pFunctionPointer)(1, 2);
}


int main()
{
	
	CFunctionPointer a;
	a.use();

	return 0;
}