C++ 解引用


获取内存地址和值

在上一页的示例中,我们使用指针变量来获取变量的内存地址(与&参考运算符)。但是,您也可以使用指针来获取变量的值,方法是使用*运算符(解引用运算符):

示例

string food = "Pizza";  // Variable declaration
string* ptr = &food;    // Pointer declaration

// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";

// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
亲自试一试 »

请注意,*符号在这里可能会令人困惑,因为它在我们的代码中做了两个不同的事情:

  • 当在声明 (string* ptr) 中使用时,它会创建一个指针变量
  • 当未在声明中使用时,它充当解引用运算符