1
| void *pVoid; // pVoid is a void pointer |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| int nValue; float fValue; struct Something { int nValue; float fValue; }; Something sValue; void *pVoid; pVoid = &nValue; // valid pVoid = &fValue; // valid pVoid = &sValue; // valid |
1
2
3
4
5
6
7
8
| 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 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| #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; } |
1
| Print(&nValue, STRING); |
0 comments: