c++ 、c
回调函数的本质是函数参数是函数指针,一般用与事件模式中,在OpenCV、OpenGL,使用库提供的注册回调函数接口,在事件发生时去执行相应的函数。
void callback_func(int a, double b);
void register_event_func(void (*f)(int, double), int value); // 注册事件函数原型
register_event_func(callback_func); // 注册回调函数实际使用方式
Java 爪哇
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer; // 注意最好用这种计时器
public class Test{
public static void main(String[] args) {
ActionListener listener = new TimerPrint();
Timer t = new Timer(10000, listener); // 用“接口”方式来替代“回调函数”,事件发生时候,执行“实现了该接口方法”的对象中的该实现方法。
t.start();
JOptionPane.showMessageDialog(null, "Quit program?"); // 进入事件等待模式
System.exit(0);
}
}
class TimerPrint implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Date date = new Date();
System.out.println("At the tone, the time is " + date);
Toolkit.getDefaultToolkit().beep();
}
}