void 指针,就是所谓的通用指针。它是一种特殊的指针,可以指向任意类型的对象。void指针的声明就像普通的指针一样:
void *pVoid; // pVoid is a void pointer
void指针可以指向任意类型的对象:
int nValue;
float fValue;
struct Something
{
int nValue;
float fValue;
};
Something sValue;
void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid
但是,void指针并不知道它所指向的具体类型,所以它不能直接拿来引用。如果要引用它,就必须明确把void指针转换成特定类型的指针。
int nValue = 5;
void *pVoid = &nValue;
// can not dereference pVoid because it is a void pointer
int *pInt = static_cast<int*>(pVoid); // cast from void* to int*
cout << *pInt << endl; // can dereference pInt
也就是说,当我们引用void指针时候,必须给出特定的引用类型。具体引用什么类型呢?这就要靠我们写程序的时候自己跟踪定义了。
#include <iostream>
enum Type
{
INT,
FLOAT,
STRING,
};
void Print(void *pValue, Type eType)
{
using namespace std;
switch (eType)
{
case INT:
cout << *static_cast<int*>(pValue) << endl;
break;
case FLOAT:
cout << *static_cast<float*>(pValue) << endl;
break;
case STRING:
cout << static_cast<char*>(pValue) << endl;
break;
}
}
int main()
{
int nValue = 5;
float fValue = 7.5;
char *szValue = "Mollie";
Print(&nValue, INT);
Print(&fValue, FLOAT);
Print(szValue, STRING);
return 0;
}