Say I have an array of void pointer pointing to objects of different types and I want to pass them through a function and cast them to pointers of their respective type, how would I go about doing this? I've tried this current code, but I get error:
'void*' is not a pointer-to-object type
objectA myObjectA;
objectB myObjectB;
objectC myObjectC;
objectD myObjectD;
void *data[4];
data[0] = static_cast<void *>( &myObjectA );
data[1] = static_cast<void *>( &myObjectB );
data[2] = static_cast<void *>( &myObjectC );
data[3] = static_cast<void *>( &myObjectD );
void dereference( void *data )
{
objectA *objA_ptr = static_cast<objectA *>( data[0] );
objectB *objB_ptr = static_cast<objectB *>( data[1] );
objectC *objC_ptr = static_cast<objectC *>( data[2] );
objectD *objD_ptr = static_cast<objectD *>( data[3] );
}
Anyone know the correct way to implement this?
edit: For context, I'm using opencv and trying to create a simple gui interface with a trackbar. Opencv allows for userdata to be fed into the TrackbarCallback which is called when the slider is moved, but only in the form of a void pointer.
int createTrackbar( const string& trackbarname, const string& winname,
int* value, int count,
TrackbarCallback onChange=0,
void* userdata=0);
Say I have an array of void pointer
void deference( void *data )
That's not an array of void pointers, it's a single void pointer.
Change that to void **
, and then since you're mixing C and C++ styles up anyway, why not just use a C style cast? :
objectA *objA_ptr = (objectA *) data[0];
Derive them all from the same base class.
make the destructors virtual if your function needs to delete them.
make your array BaseClass *data[4]
make your function void deference(BaseClass **data)
您可以使用reinterpret_cast<>()
而不是static_cast<>
。
The correct function prototype needs to be
void dereference(void **data)
since you're passing an array of void *
, and as we all know in C and C++ an array expression is replaced with a pointer expression in most circumstances.
Is there any particular reason why you must use an array of pointers to objects of differing classes? This smells like a C solution to a C++ problem.
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.