- C++ 基础
- C++ 首页
- C++ 概述
- C++ 环境设置
- C++ 基本语法
- C++ 注释
- C++ Hello World
- C++ 省略命名空间
- C++ 常量/字面量
- C++ 关键字
- C++ 标识符
- C++ 数据类型
- C++ 数值数据类型
- C++ 字符数据类型
- C++ 布尔数据类型
- C++ 变量类型
- C++ 变量作用域
- C++ 多个变量
- C++ 基本输入/输出
- C++ 修饰符类型
- C++ 存储类
- C++ 运算符
- C++ 数字
- C++ 枚举
- C++ 引用
- C++ 日期和时间
- C++ 控制语句
- C++ 决策制定
- C++ if 语句
- C++ if else 语句
- C++ 嵌套 if 语句
- C++ switch 语句
- C++ 嵌套 switch 语句
- C++ 循环类型
- C++ while 循环
- C++ for 循环
- C++ do while 循环
- C++ foreach 循环
- C++ 嵌套循环
- C++ break 语句
- C++ continue 语句
- C++ goto 语句
- C++ 构造函数
- C++ 构造函数和析构函数
- C++ 复制构造函数
C++ 解引用
在 C++ 中,解引用是指帮助访问 指针 所指向的值的过程。其中指针存储该特定值的内存地址。要访问或修改存储在该地址处的值,可以使用由 (*) 表示的解引用运算符。
解引用以读取值
以下是访问存储在指针指向的地址处的值的语法:
Type value = *pointer; // Gets the value at the address pointed to by the pointer
解引用以修改值
解引用运算符的语法,用于修改指针指向的地址处的值:
*pointer = newValue; // Sets the value at the address pointed to by the pointer
C++ 解引用的示例
以下是一个说明 C++ 中解引用的简单示例:
#include <iostream>
using namespace std;
int main() {
int number = 42; // A normal integer variable
int* ptr = &number; // Pointer that holds the address of 'number'
// Dereferencing to read the value
cout << "Original Value: " << *ptr << endl;
// Dereferencing to modify the value
*ptr = 100;
cout << "Modified Value: " << number << endl;
return 0;
}
输出
Original Value: 42 Modified Value: 100
解释
- 首先,我们声明了一个名为 number 的整数变量,并将其初始化为值 42。
- 声明了一个数据类型为整数的指针 ptr。使用取地址运算符 & 将指针分配给 number 的地址,这意味着 ptr 将指向 number 的内存地址位置。
- 现在,我们使用解引用运算符 * 来访问存储在 ptr 指向的地址处的值。
- *ptr = 100; 此行再次使用解引用运算符,但这次用于赋值新值。
引用与解引用
| 引用 | 解引用 | |
|---|---|---|
| 定义 | 引用 是另一个变量的变量,它允许您访问或修改原始变量,而无需直接使用其名称。 | 解引用是访问指针保存的内存地址处存储的值的过程。 |
| 符号 | & (用于声明) | * (用于表达式) |
| 语法 | dataType& referenceName = existingVariable; | dataType pointerVariable = *pointerName; |
显示引用和解引用的示例
以下是一个在代码中同时说明引用和解引用的示例。
#include <iostream>
using namespace std;
int main() {
int number = 42;
// Pointer holding the address of 'number'
int* ptr = &number;
// Reference to 'number'
int& ref = number;
// Using pointer to read the value (dereferencing ptr)
cout << "Original Value (pointer): " << *ptr << endl;
// Using reference to read the value
cout << "Original Value (reference): " << ref << endl;
// Modifying the value through the pointer (dereferencing ptr)
*ptr = 100;
cout << "Modified Value (pointer): " << number << endl;
cout << "Modified Value (reference): " << ref << endl;
// Modifying the value through the reference
ref = 200;
cout << "Modified Value (reference): " << number << endl;
cout << "Modified Value (pointer): " << *ptr << endl;
return 0;
}
输出
Original Value (pointer): 42 Original Value (reference): 42 Modified Value (pointer): 100 Modified Value (reference): 100 Modified Value (reference): 200 Modified Value (pointer): 200
广告