在C++的类中使用类成员函数作为回调函数

由于类有隐式的this指针,所以不能直接把类成员函数作为回调函数使用。现用一例子来展示如何在类中使用类成员函数作为回调函数。

此例子仅用于展示如何在类中使用类成员函数作为回调函数
代码如下:

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>

class MyTest
{
public:
    MyTest() {};
    ~MyTest() {};

    void ThreadFunc();

    static unsigned int __stdcall Threadcallback(PVOID Pm);

    void printf();

private:
    static MyTest* p;//用于在回调函数中调用类成员函数
};

void MyTest::ThreadFunc()
{
    //第四个参数自定义,多个参数可通过结构体传递
    _beginthreadex(NULL, 0, Threadcallback, NULL, 0, NULL);
}

MyTest* MyTest::p = NULL;
unsigned int __stdcall MyTest::Threadcallback(PVOID Pm)
{
    std::cout << "回调函数" << std::endl;

    //调用了非静态成员函数,在这个函数里面实现自己的功能
    p->printf();

    return 0;
}

void MyTest::printf()
{
    std::cout << "测试函数" << std::endl;
}

int main()
{
    MyTest mytest = MyTest();
    for(int i = 0; i < 5; i++)
        mytest.ThreadFunc();
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34248512/article/details/77036448