C++ 指向void的指针

在继续本教程之前,请务必查看 C++ 指针

在 C++ 中,我们不能将一种数据类型的变量的地址分配给另一种数据类型的指针。请看这个例子

// pointer is of int type
int *ptr;

// variable is of double type
double d = 9.0;

// Error
// can't assign double* to int*
ptr = &d;

这里,之所以出现错误,是因为该地址是一个 double 类型变量。然而,该指针是 int 类型的。

在这种情况下,我们可以在 C++ 中使用 **void 指针**(void pointers)。例如:

// void pointer
void *ptr;

double d = 9.0;

// valid code
ptr = &d;

void 指针是一种通用指针,当不知道指针所指向变量的数据类型时使用。


示例 1:C++ Void 指针

#include <iostream>
using namespace std;

int main() {
    void* ptr;
    float f = 2.3f;

    // assign float address to void
    ptr = &f;

    cout << &f << endl;
    cout << ptr << endl;

    return 0;
}

输出

0xffd117ac
0xffd117ac

这里,指针 ptr 被赋予了 &f 的值。

输出显示,void 指针 ptr 存储了 float 类型变量 f 的地址。


由于 void 是一个空类型,void 指针不能被解引用。

void* ptr;
float* fptr;
float f = 2.3;

// assign float address to void pointer
ptr = &f;
cout << *ptr << endl;  // Error

// assign float address to float pointer
fptr = &f;
cout << *fptr << endl;   // Valid

示例 2:打印 Void 指针的内容

要打印 void 指针的内容,我们使用 static_cast 运算符。它将指针从 void* 类型转换为指针正在存储的地址的相应数据类型。

#include <iostream>
using namespace std;

int main() {
  void* ptr;
  float f = 2.3f;

  // assign float address to void pointer
  ptr = &f;

  cout << "The content of pointer is ";
  // use type casting to print pointer content
  cout << *(static_cast<float*>(ptr));

  return 0;
}

输出

The content of pointer is 2.3

此程序打印 void 指针 ptr 所指向地址的值。

由于我们不能解引用 void 指针,所以我们不能使用 *ptr

但是,如果我们把 void* 指针类型转换为 float* 类型,我们就可以使用 void 指针所指向的值。

在此示例中,我们使用 static_cast 运算符将指针的数据类型从 void* 转换为 float*


C 风格转换

我们也可以使用 C 风格转换来打印值。

// valid
cout << *((float*)ptr);

但是,static_cast 比 C 风格转换更受推荐。


注意: void 指针不能用于存储具有 constvolatile 限定符的变量的地址。

void *ptr;
const double d = 9.0;

// Error: invalid conversion from const void* to void*
ptr = &d;
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战