C++基础-结构体伪函数与多线程(void operator()(int))

C++结构体的伪函数使用operator进行创建,使用void operator()(int) 来表示需要传入的参数 

#include<iostream>
using namespace std;
struct func{ void operator()() //方法, 可以将对象名当做函数名使用 { cout << "hello china hello cpp" << endl; } void operator()(int i) { cout << "hello china hello cpp" << i << endl; } }; int main() { func f1; f1(); f1(1); func f2; f2(); cin.get(); }

伪函数与多线程,使用伪函数可以在创建的时候执行任务,个人理解,相当于是构造函数

#include <iostream>
#include<thread>
#include<windows.h>

using namespace std;

struct MyStruct
{
    MyStruct()
    {
        cout << "create" << endl;
    }

    ~MyStruct()
    {
        cout << "endl" << endl;
    }

    void operator()()
    {
        MessageBoxA(0, "ABCDEFG", "123", 0);
    }
};
int main()
{
    MyStruct go1;
    thread t1(go1);

    MyStruct go2;
    thread t2(go1);

//    thread t3(MyStruct()); //不适合作为多线程参数, 因为销毁的太快了

//    MyStruct *p = new MyStruct();

//    int a(5);
//    int *p = new int(5); //()初始化,
    //MyStruct 构造函数, 构造一个临时对象, 匿名对象
    MyStruct()();

    cin.get();
}
原文地址:https://www.cnblogs.com/my-love-is-python/p/14940407.html