这些代码行显示以下错误:
int e = 5, * ePtr = &e;
void * vPtr = ePtr;
cout << *vPtr;
语法错误:
`void*' is not a pointer-to-object type
我知道:
- 任何指针类型都可以存储在 void 指针类型中而无需显式转换
- 解引用无效指针的尝试是一个语法错误
但是如果我们不能做到第 2 点,那么第 1 点除了在语法上正确之外还有什么用?我想使用 vPtr
打印 5(即 e
)..这可能吗?
这很好用:
int e = 5, * ePtr = &e;
void * vPtr = ePtr; //specific to generic Ok!
double * dPtr = (double *)vPtr; //to let compiler know stoarge size
cout << *dPtr; //indirectly it is vPtr i.e. a void ptr, can be deref only if cast
最佳答案
要引用 void*
指针,您需要将指针转换回兼容类型。
void*
指针在 C 中经常使用,但是,由于在 C++ 中我们可以进行函数重载和多态性,因此它们的使用受到更多限制。
在 C 中使用 void*
指针的一个很好的例子是使用回调的函数:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
当您调用 pthread_create 函数时,它会调用您的 start_routine
。
在这种情况下,您可能希望将一些数据传递给您的 start_routine
。由于线程库无法为您可能希望传递给回调的每种类型声明 pthread_create 函数,因此使用 void*
类型。
void myCallBack(void* arg) {
int* value = (int*)arg;
/* Do something with value: it is an int* now*/
printf("Message from callback %d\n", *value);
}
/* Some main function or whatever... */
{
/* ... */
int foo = 123;
ret = pthread_create(&thread, &attr,myCallBack, &foo);
/* ... */
}
关于C++ 取消引用 void 指针,将 int ptr 转换为 void ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16830042/