当前位置:网站首页 > 技术博客 > 正文

指针c++语言



声明时,变量前加 "基本类型 &" :声明引用变量。它是某个已存在变量的别名,即该引用变量名称与原始变量名称都代表同一个变量。

声明时,变量前加 "基本类型 *" :声明指针变量。它的值是另一个变量的地址

声明时,变量前加 "基本类型 ":声明二级指针变量。它的值是另一个一级"基本类型 *"指针变量的地址 (指针的指针)。

调用时,变量前加 "&" :使用取地址运算符获取该变量的地址

调用时,指针变量前加 "*" :使用间接寻址运算符获取该指针变量所指向的变量

调用时,二级指针变量前加 "" :获取该二级指针变量所指向的指针所指向的变量

示例:

#include <iostream> using namespace std; int main(){ int var; // 声明int类型变量var int * ptr; // 声明指针变量ptr ptr = &var; // 先使用 & 运算符获取变量var的地址,再把该地址赋值给指针变量ptr int pptr; // 声明二级指针变量pptr pptr = &ptr; // 先使用 & 运算符获取变量ptr的地址,再把该地址赋值给二级指针变量pptr int & ref1 = var; // 声明引用变量ref1, ref1是变量var的别名(引用必须在创建时被初始化) int & ref2 = *ptr; // 先使用*运算符获取指针变量ptr所指向的变量(即var),再用该变量(var)初始化引用变量ref2(声明引用变量ref2的同时对它进行初始化)。也就是说,该行代码执行后,ref2也是变量var的别名 var = 20 cout << "Value of var: "; cout << var << endl; cout << "Value of &var: "; cout << &var << " (var的地址)" << endl; cout << endl; cout << "Value of ptr: "; cout << ptr << " (等于&var)" << endl; cout << "Value of *ptr: "; cout << *ptr << " (等于var)" << endl; cout << "Value of &ptr: "; cout << &ptr << " (ptr的地址)" << endl; cout << endl; cout << "Value of pptr: "; cout << pptr << " (等于&ptr)" << endl; cout << "Value of *pptr: "; cout << *pptr << " (等于ptr, 等于&var)" << endl; cout << "Value of pptr: "; cout << pptr << " (等于*ptr, 等于var)" << endl; cout << "Value of &pptr: "; cout << &pptr << " (pptr的地址)" << endl; cout << endl; cout << "Value of ref1: "; cout << ref1 << " (等于var)" << endl; cout << "Value of &ref1: "; cout << &ref1 << " (等于&var)" << endl; cout << endl; cout << "Value of ref2: "; cout << ref2 << " (等于var)" << endl; cout << "Value of &ref2: "; cout << &ref2 << " (等于&var)" << endl; return 0; } 

输出结果:

Value of var: 20 Value of &var: 0x7ffce63490bc (var的地址) Value of ptr: 0x7ffce63490bc (等于&var) Value of *ptr: 20 (等于var) Value of &ptr: 0x7ffce63490b0 (ptr的地址) Value of pptr: 0x7ffce63490b0 (等于&ptr) Value of *pptr: 0x7ffce63490bc (等于ptr, 等于&var) Value of pptr: 20 (等于*ptr, 等于var) Value of &pptr: 0x7ffce63490a8 (pptr的地址) Value of ref1: 20 (等于var) Value of &ref1: 0x7ffce63490bc (等于&var) Value of ref2: 20 (等于var) Value of &ref2: 0x7ffce63490bc (等于&var)

版权声明


相关文章:

  • mysql日期加天数等于日期2025-08-06 12:29:59
  • c++bitset头文件2025-08-06 12:29:59
  • -i++什么意思2025-08-06 12:29:59
  • bash history2025-08-06 12:29:59
  • 键值对什么意思2025-08-06 12:29:59
  • raas和ras一样吗2025-08-06 12:29:59
  • 火鸟字幕汉化组直装2025-08-06 12:29:59
  • swap c语言2025-08-06 12:29:59
  • fastjson教程2025-08-06 12:29:59
  • centos 性能监控工具2025-08-06 12:29:59