C++定义回调函数

目录结构:

C++定义回调函数_第1张图片

 

call.h

#ifndef MY_CALL
#define MY_CALL


class MYCALL {
public:
	double callback(double(*)(double, double), double, double);
	// 或使用 ↓
	// double callback(std::function, double, double);

	template
	double callback(T* ptr, double(T::* call)(double, double), double x, double y) {
		return (ptr->*call)(x, y);
	}
};


#endif

call.cpp

#include "call.h"


double MYCALL::callback(double(*call)(double, double), double x, double y) {
	return call(x, y);
}

/***
或使用 ↓
#include 
double MYCALL::callback(std::function call, double x, double y) {
	return call(x, y);
}
***/

demo.h

#ifndef MY_DEMO
#define MY_DEMO


class MYDEMO {
private:
	double x;
	double y;
public:
	MYDEMO(double, double);
	~MYDEMO();
	double sum(double, double);
	double mul(double, double);
};


double sum(double, double);

double mul(double, double);


#endif

demo.cpp

#include 
#include "demo.h"

using namespace std;


MYDEMO::MYDEMO(double x, double y) {
	this->x = x;
	this->y = y;
}

MYDEMO::~MYDEMO() {
	cout << "类XYDEMO对象已析构!" << endl;
}

double MYDEMO::sum(double x, double y) {
	return x + y + this->x + this->y;
}

double MYDEMO::mul(double x, double y) {
	return x * y * this->x * this->y;
}

double sum(double x, double y) {
	return x + y;
}

double mul(double x, double y) {
	return x * y;
}

main.cpp

#include 
#include 
#include "call.h"
#include "demo.h"

using namespace std;


int main() {
	MYCALL* my_call = new MYCALL();

	list> mylist{
		{1, 2}, {11, 22}, {111, 222}, {1111, 2222}
	};

	cout << "开始执行 sum 函数。\n";
	for (auto i : mylist) {
		cout << my_call->callback(sum, i.first, i.second) << endl;
	}

	cout << "开始执行 mul 函数。\n";
	for (auto i : mylist) {
		cout << my_call->callback(mul, i.first, i.second) << endl;
	}

	MYDEMO* my_demo = new MYDEMO(3, 9);

	cout << "开始执行 MYDEMO::sum 函数。\n";
	for (auto i : mylist) {
		cout << my_call->callback(my_demo, &MYDEMO::sum, i.first, i.second) << endl;
	}

	cout << "开始执行 MYDEMO::mul 函数。\n";
	for (auto i : mylist) {
		cout << my_call->callback(my_demo, &MYDEMO::mul, i.first, i.second) << endl;
	}

	if (my_call) {
		delete my_call;
		my_call = nullptr;
	}
	if (my_demo) {
		delete my_demo;
		my_demo = nullptr;
	}

	cout << "演示结束!\n";

	return 0;
}

运行结果:

C++定义回调函数_第2张图片

你可能感兴趣的:(C++)