每个成员函数(除了在第 12.6 节介绍的 static 成员函数外)都有一个额外的、隐含的形参 this。
为了理解成员函数的调用,可考虑下面的语句:
total.same_isbn(trans);
就如编译器这样重写这个函数调用,this指针被传入成员函数:
Sales_item::same_isbn(&total, trans);
所以在进行多线程编程的时候遇到了一个编译问题:argument of type ‘void* (test::)(void*)’ does not match ‘void* (*)(void*)’
后来发现将线程处理函数声明为static类型,问题得解。
其实这个原因很简单,当把线程函数封装在类中,this指针会作为默认的参数被传进函数中,从而和线程函数参数(void*)不能匹配,不能通过编译。
另一种理解
类的静态函数不属于该类的任何一个对象,而是属于类本身,所以不受对象局部变量的影响,在运行时可以直接调用类的静态函数,从而启动线程!
为了理解成员函数的调用,可考虑下面的语句:
total.same_isbn(trans);
就如编译器这样重写这个函数调用,this指针被传入成员函数:
Sales_item::same_isbn(&total, trans);
所以在进行多线程编程的时候遇到了一个编译问题:argument of type ‘void* (test::)(void*)’ does not match ‘void* (*)(void*)’
后来发现将线程处理函数声明为static类型,问题得解。
其实这个原因很简单,当把线程函数封装在类中,this指针会作为默认的参数被传进函数中,从而和线程函数参数(void*)不能匹配,不能通过编译。
另一种理解
类的静态函数不属于该类的任何一个对象,而是属于类本身,所以不受对象局部变量的影响,在运行时可以直接调用类的静态函数,从而启动线程!
相反,如果一个类的一个局部对象的生命周期结束了,难道线程函数就不能用了吗?
#include<iostream>
#include <pthread.h>
using namespace std;
class test
{
public:
int testnum;
test();
~test();
void doPthread();
static void * createPthread(void *ptr);
};
test::test()
{
testnum=1;
}
test::~test()
{
}
void test::doPthread()
{
cout << "create_thread" << endl;
pthread_t pthread;
pthread_create(&pthread, NULL, createPthread, (void*)this );
cout << "pthread_join" << endl;
pthread_join(pthread, NULL);
cout << "end" << endl;
}
void *test::createPthread(void *ptr)
{
test* tp = (test *)ptr;
while(1)
cout << tp->testnum << endl;
}
int main()
{
test t;
t.doPthread();
return 0;
}