0
点赞
收藏
分享

微信扫一扫

使用类的运算符重载(可调用对象)作为线程入口函数

火热如冰 2022-01-31 阅读 8
#include <iostream>
#include <string>
using namespace std;
class A {
public:
	A(int a) {
		std::cout << "构造函数执行了" << "this = " << this << " threadid = " << std::this_thread::get_id() << std::endl;
	}
	A(const A& a) {
		std::cout << "拷贝构造函数执行了" << "this = " << this << " threadid = " << std::this_thread::get_id() << std::endl;
	}
	~A() {
		std::cout << "析构函数执行了" << "this = " << this << " threadid = " << std::this_thread::get_id() << std::endl;
	}
public:
	void operator()(int ab)
	{
		std::cout << ab << std::endl;
		std::cout << "子线程ID = " << std::this_thread::get_id() <<std::endl;
	}
};

int main()
{
	A a(1);
	std::thread obj(a,1);
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	obj.join();
}

在这里插入图片描述

#include <iostream>
#include <string>
using namespace std;
class A {
public:
	A(int a) {
		std::cout << "构造函数执行了" << "this = " << this << " threadid = " << std::this_thread::get_id() << std::endl;
	}
	A(const A& a) {
		std::cout << "拷贝构造函数执行了" << "this = " << this << " threadid = " << std::this_thread::get_id() << std::endl;
	}
	~A() {
		std::cout << "析构函数执行了" << "this = " << this << " threadid = " << std::this_thread::get_id() << std::endl;
	}
public:
	void operator()(int ab)
	{
		std::cout << ab << std::endl;
		std::cout << "子线程ID = " << std::this_thread::get_id() <<std::endl;
	}
};

int main()
{
	A a(1);
	std::thread obj(std::ref(a),1);//使用&a编译不通过
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	obj.join();
}

在这里插入图片描述

举报

相关推荐

0 条评论