Accessing non static members inside static method via passed pointer

Not the actual code, but a representation:

I need to initiate a thread from one of my member functions and I do that this way:

return_val = pthread_create(&myThread, NULL, myStaticMethod, (void*)(this));

i) I pass this as an argument because static methods do not allow non-static members to be accessed, and since I have non-static methods and members to access inside the static method. Is this right? Or, are there any other alternatives?

myStaticMethod(void* args)    
{
    args->myPublicMethod(); //Is this legal and valid?

    args->myPrivateMember;   //Is this legal and valid?
}

I get an error saying void* is not a pointer to object type , and I think that args is to be typecast into an instance of type myClass .

But, how do I do that?


args->myPublicMethod(); //Is this legal and valid?

No. That is neither legal nor valid. However, you can use:

reinterpret_cast<MyClass*>(args)->myPublicMethod();

You can access a private member function of a class from a static member function. So, you can access a private member of the class using:

reinterpret_cast<MyClass*>(args)->myPrivateMember;

Another SO question and its answers discuss the pros and cons of using static_cast and reinterpret_cast . Since you are using void* as the intermediate type, you can use either of them.

链接地址: http://www.djcxy.com/p/17302.html

上一篇: 方法和功能的区别?

下一篇: 通过传入的指针访问静态方法内的非静态成员