#include<iostream>#include<cassert>enumclassType{tInt,// note: we can't use "int" here because it's a keyword, so we'll use "tInt" insteadtFloat,tCString};voidprintValue(void*ptr,Typetype){switch(type){caseType::tInt:std::cout<<*static_cast<int*>(ptr)<<'\n';// cast to int pointer and perform indirectionbreak;caseType::tFloat:std::cout<<*static_cast<float*>(ptr)<<'\n';// cast to float pointer and perform indirectionbreak;caseType::tCString:std::cout<<static_cast<char*>(ptr)<<'\n';// cast to char pointer (no indirection)// std::cout will treat char* as a C-style string// if we were to perform indirection through the result, then we'd just print the single char that ptr is pointing tobreak;default:assert(false&&"type not found");break;}}intmain(){intnValue{5};floatfValue{7.5f};charszValue[]{"Mollie"};printValue(&nValue,Type::tInt);printValue(&fValue,Type::tFloat);printValue(szValue,Type::tCString);return0;}
输出结果:
123
5
7.5
Mollie
void 指针其他细节
void 指针可以被设置为 null 值:
1
void*ptr{nullptr};// ptr is a void pointer that is currently a null pointer