如何打印const void*的值

Rac*_*hel 1 c++

#include <iostream>
using namespace std;

void fn(const void *l) {
    // How to print the value of l. The below line is giving error
    cout << "***" << *l;
}

int main() {
    cout << "Hello World!";
    int d = 5;

    fn((char *) &d);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

在函数'void fn(const void*)'中:第8行:错误:'const void*'不是由于-Wfatal-errors而终止的指针对象类型编译.

尝试铸造如下图所示.它没有帮助.请提供建议.

#include <iostream>
using namespace std;

void fn(const void *l) {
    // How to print the value of l. The below line is giving error
    int *pInt = static_cast<char*>(l);
    cout << *pInt;
}

int main() {
    cout << "Hello World!";
    int d = 5;

    fn((char *) &d);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在函数'void fn(const void*)'中:第9行:错误:从'const void*'类型的static_cast到'char*'类型由于-Wfatal-errors而导致constness编译终止

Mac*_*iek 6

您想显示指针本身的值或它指向的值吗?在第一种情况下,简单

 cout << p;
Run Code Online (Sandbox Code Playgroud)

足够了.如果你想要实现第二件事 - 它是不可能的 - 指针指向void,并且它不能被解除引用,因为编译器不知道其后面隐藏的值的类型.


Luc*_*ore 5

你不能.除非你将void指针解释为某种东西.

把自己放在功能的鞋子里:我给你一个指向"某事"的指针.你不知道那是什么东西.我告诉你打印那个东西.你是做什么?