在 C++ 中如何打印 void 指针的值?
首先需要说明的是,void 指针是一种特殊的指针,它可以存储任意数据类型的地址。因此,如果要打印 void 指针的值,必须知道它所指向的数据类型。
下面是一个实现代码示例:
#include<iostream>
using namespace std;
void print_value(void *ptr, string type)
if (type == "int") {
cout << *((int*)ptr) << endl;
else if (type == "float") {
cout << *((float*)ptr) << endl;
// ... 你可以继续添加其他数据类型的判断语句
int main()
int a = 42;
float b = 3.14f;
void *p1 = &a, *p2 = &b;
print_value(p1, "int");
print_value(p2, "float");
return 0;
上面的代码使用了一个名为 print_value
的函数,它接受两个参数:一个是 void 指针,一个是字符串类型的参数。通过字符串类型的参数,我们可以判断要打印的数据类型,然后对指针进行强制类型转换,最后通过解除引用来打印该指针所指向的值。