Tag: ATI return match requires static member color object-oriented names span
1. Problem arises
I want to translate my C program into C + +, because I think C + + 's object-oriented approach is particularly useful.
And then I started porting, and when I wanted to call pthread_create in a class function to create a class.
The parameters I gave are
S=pthread_create (&id,null,run,null); // function Prototypes void * Thread_433::run (void *arg) { void * ret; using namespace std; cout<<"hello!\r\n"; return ret;}
This time it will compile error,
D:\Cprogress\pthread\my_thread.cpp:'thread_433::run' from' void* (thread_433::) (void*)"void* (*) (void*)' s =pthread_create (&id,null,run,null); ^
He says this type does not match.
2. Problem solving
There is a type mismatch problem. Because pthread_create requires a parameter type of void* (*) (void*), and run acts as a member function of the class, its type is a member function pointer of void* (thread_433::) (void*).
We know that the member functions of a class will become a global function with the this pointer parameter after being processed by the compiler, so the type is doomed to be mismatched.
However, if you declare run as a static type, the compiler converts the static form of a function into a global function without the this pointer, so its type can match the type of parameter that Pthread_create requires. However, a static member function of a class cannot access a non-static member of a class, but this can be resolved by passing the this pointer.
Modified code: No other need to change
voidThread_433::init (void){ ints; S=pthread_create (&id,null,thread_433::run,null); if(s!=0) Std::cout<<"err!\r\n";}/********** class declaration ***********/classthread_433{ Public: thread_433 (); voidInit (void); voidDelete (void);Private: pthread_t ID; Static void*run (void*arg);};
When C + + calls the Pthread_create function, the members in the incoming class error. Workaround.