FLTK中如何从一个函数内部传递数据到另一个函数的方法及实例
时间: 2023-05-28 11:05:54 浏览: 51
在FLTK中,可以使用全局变量或者回调函数来传递数据。
1. 全局变量
定义一个全局变量,在一个函数内部赋值,然后在另一个函数中使用即可。
示例代码:
```cpp
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
int count = 0; // 定义全局变量
void increment_count() {
count++;
}
void print_count() {
printf("count: %d\n", count);
}
int main() {
Fl_Window window(200, 100, "FLTK Example");
Fl_Button button(10, 10, 80, 25, "Increment");
button.callback(increment_count);
Fl_Button button2(100, 10, 80, 25, "Print");
button2.callback(print_count);
window.show();
return Fl::run();
}
```
2. 回调函数
可以在一个函数内部定义一个回调函数,并将其作为参数传递给另一个函数。在回调函数中,可以进行数据的处理,并将处理结果传递给原函数。
示例代码:
```cpp
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Button.H>
void print_count(int count) {
printf("count: %d\n", count);
}
void increment_count(void* data) {
int* count = static_cast<int*>(data);
(*count)++;
}
int main() {
Fl_Window window(200, 100, "FLTK Example");
int count = 0;
Fl_Button button(10, 10, 80, 25, "Increment");
button.callback(increment_count, &count); // 将回调函数和数据传递给按钮
Fl_Button button2(100, 10, 80, 25, "Print");
button2.callback(print_count, &count); // 将回调函数和数据传递给按钮
window.show();
return Fl::run();
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)