面向对象程序设计-C++_课时21引用

数据类型 & 别名=对象名;

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int * f(int * x)
 5 {
 6     (*x)++;
 7     return x;
 8 }
 9 
10 int & g(int & x)
11 {
12     x++;
13     return x;
14 }
15 
16 int x;
17 
18 int & h()
19 {
20     int q;//!return q
21     return x;
22 }
23 
24 void main()
25 {
26     int a = 0;
27     std::cout << a << std::endl;//0
28 
29     f(&a);//丑陋,但是清晰
30     std::cout << a << std::endl;//1
31 
32     g(a);//清晰,但是隐蔽,可以修改a
33     std::cout << a << std::endl;//2
34 
35     h() = 16;//返回值是引用,因此可以做左值
36     std::cout << a << std::endl;//2
37 
38     std::cout << x << std::endl;//16
39 
40     system("pause");
41 }

不能声明引用的引用

可以声明对指针的引用,但不能声明指针对变量的引用

int & * p;//illegal

int * & p1=p2;//ok

void f(int * & p);

p是引用,引用了一个指向int类型的指针

可以声明指向引用的指针

没有引用的数组(数组元素不能是引用)

但是可以引用一个数组

原文地址:https://www.cnblogs.com/denggelin/p/5635443.html