美文网首页
C++类的线程函数为什么要加static修饰

C++类的线程函数为什么要加static修饰

作者: mengfanle | 来源:发表于2020-04-26 13:49 被阅读0次

    首先看下面这个类

    class CMyTest
    {
    public:
    CMyTest();
    ~CMyTest();

    DWORD   Start();
    static DWORD WINAPI ThreadFun(LPVOID);
    
    // ....
    

    };

    void main()
    {
    CMyTest test;
    // .....
    }

    ThreadFun(LPVOID) 为什么要加static修饰呢!
    原来非静态成员函数都会在参数列表中加上一个this指针为为参数, 这样的话你写的线程函数就不符合调用规定了.

    比如 DWORD WINAPI ThreadFun(LPVOID); 是非静态的,实际编译后,就会变成
    DWORD WINAPI ThreadFun(LPVOID, CMyClass *this);

    这个函数就明显不能作为线程的函数了, 因为多了个参数.所以编译就过不了了.
    加上static修饰后,类的成员函数就不会被加上默认的this参数,所以就符合调用规定了。

    相关文章

      网友评论

          本文标题:C++类的线程函数为什么要加static修饰

          本文链接:https://www.haomeiwen.com/subject/hdidwhtx.html