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

2021/6/27 14:14:22

本文主要是介绍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();
}

 



这篇关于C++基础-结构体伪函数与多线程(void operator()(int))的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程