c++学习(八、函数指针和线程)
目录
一、一般函数指针
1. 使用方法
2.注意事项
二.成员函数指针
1.使用方法(指定作用域)
2.调用方法(生成对象,根据对象调用)
三、函数与线程
1.使用 boost::bind 创建函数对象
2.类中引入指针管理线程
一、一般函数指针
1. 使用方法
using FuncPtr = int (*)(int, int);FuncPtr funcPtr = &add;
2.注意事项
函数指针调用时候应该是
int result = (*funcPtr)(3, 4);
但是为了方便也可以
int result = funcPtr(3, 4);
#include <iostream>// 普通函数
int add(int a, int b) {return a + b;
}int main() {// 定义函数指针类型using FuncPtr = int (*)(int, int);// 获取函数地址并赋值给函数指针FuncPtr funcPtr = &add;// 通过函数指针调用函数// int result = funcPtr(3, 4);int result = (*funcPtr)(3, 4);std::cout << "Result: " << result << std::endl;return 0;
}
二.成员函数指针
1.使用方法(指定作用域)
using MemberFuncPtr = int (Calculator::*)(int, int);// 获取成员函数地址MemberFuncPtr memberFuncPtr = &Calculator::add;
2.调用方法(生成对象,根据对象调用)
Calculator calc;// 通过成员函数指针调用成员函数int result = (calc.*memberFuncPtr)(3, 4);
三、函数与线程
1.使用 boost::bind 创建函数对象
对于auto boundFunc = boost::bind(&CBSROS::updateObstacleThread, this);,this是对象,updateObstacleThread是成员函数,有对象有成员函数,绑定在一起返回一个函数,可以直接调用这个函数了,就相当于调用当前成员的成员函数。
#include <iostream>
#include <boost/bind.hpp>class CBSROS {
public:void updateObstacleThread() {std::cout << "Updating obstacle state..." << std::endl;}void testBindCall() {// 使用 boost::bind 创建函数对象auto boundFunc = boost::bind(&CBSROS::updateObstacleThread, this);// 直接调用函数对象boundFunc();}
};int main() {CBSROS cbsRos;cbsRos.testBindCall();return 0;
}
2.类中引入指针管理线程
update_obstacle_thread_ =new boost::thread(boost::bind(&CBSROS::updateObstacleThread, this));
上面的代码相当于创建了一个线程类,线程类里面执行的是当前对象的成员函数,之后找到一个指针来指向这个线程类,用来管理线程,比如让线程开始或者结束等。。。