Home cpp reference
Post
Cancel

cpp reference

C++中的引用相当于别名

Example

1
2
3
4
5
6
int age = 10;
// 引用, refAge相当于age的别名
int &refAge = age;
refAge = 20;
// c pointer
int *agePtr = &age;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void swap1(int* a, int* b) {
  int tmp = *a;
  *a = *b;
  *b = tmp;
}

void swap2(int& a, int& b) {
  int tmp = a;
  a = b;
  b = tmp;
}

int main() {
  int a = 10;
  int b = 20;
  swap1(&a, &b);
  swap2(a, b)
  return 0;
}

Note

  • 在定义引用的时候就必须初始化,且不可改变(从一而终)
  • 引用的本质就是指针,只是编译器弱化了其功能,所以引用可以认为是弱化了的指针

References

https://ke.qq.com/webcourse/336509/100476446#taid=3185744747504253&vid=5285890793624807124

This post is licensed under CC BY 4.0 by the author.