1. 概要
取址符号&
读音:and
- 单个常量取址时,必须要加取址符号&
- 数组取址时,不需要加&符号,默认取数组第一个元素地址
2. 代码实现
2.1 取址
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
//关于取址符号and:&
int num = 6;
int nums[] = {1,2,3};
int* ptr_num = #//单个常量取址时,必须要加取址符号&
int* ptr_nums = nums;//数组取址时,不需要加&符号,默认取数组第一个元素地址
cout << ptr_num << '\t' << ptr_nums << endl;
cout << *ptr_num << '\t' << *ptr_nums;
return 0;
}
- 程序输出
0x66ff1c 0x66ff00
6 1
Process returned 0 (0x0) execution time : 0.047 s
Press any key to continue.
2.2 引用
&
也是引用符号
int num = 5;
int& num1 = num;
cout << &num1;
//等价于指针,实际上引用在编译时就会被编译成指针
int num = 5;
int* num2 = #
cout << num2;
引用的时候最好是引用变量,如果时引用常量,除了上面哪种方法,还可以这样
const int& num1 = 5;//指定引用的是常量
cout << &num1;