简体   繁体   中英

converting const void* pointer to specific class pointer

I have function declaration as below

void func1(const void& * pThis) {
    MyClass* pMyClass = static_cast<MyClass*>(pThis);    //....I use PMyClass pointer.
}

I am getting error cannot convert const void* to MyClass*

How to do this step?

You can

MyClass* pMyClass = const_cast<MyClass*>( static_cast<const MyClass*>(pThis) );

But this awful syntax is the hint: why then the function has a const argument, wouldn't you want it to be like

void func1(void * pThis) {

Of course, you can take a shortcut using C-style cast:

MyClass* pMyClass = (MyClass*)pThis;

but I would fix the design instead if possible.

The const is the problem. It can't be cast away using static_cast . Given you're casting it into a non-const MyClass , there's no use in accepting a const argument anyway. You can use const_cast to remove the const-ness, but that would be bad - your method declares it is not going to change the argument, but it is in fact changing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM