引用(References)

  引用(References

引用指 一个对象的另一个名字,他的地址和原对象是一样的。引用主要被用来表示函数的参数和返回值,特别是为了运算符的重载。
下面用代码说明引用的基本概念:
void referencesTest(){
       int a = 0;
       int& b = a;
       cout<<&a<<" "<<a<<"/n";
       cout<<&b<<" "<<b<<"/n";
       b++;
       cout<<"/n"<<&a<<" "<<a<<"/n";
       cout<<&b<<" "<<b<<"/n";
}
输出如下:
       0012FF24       0
0012FF24       0
 
0012FF24       1
0012FF24       1

 int a = 12;
 int &ra = a;
   
 int &rr1 = ra; // OK!
// int &&rr2 = ra; // error!
 cout << rr1 <<endl;
 rr1 = 3;
 cout << a << " " << ra << " " << rr1 << endl;
//输出结果rr1: 12
// a b c:       3  3  3
   
// int &*pri; // error!  //不允许对指针的引用
// int &ar[3]; // error! //不允许对数组的引用

References can't be const or volatile, because aliases can't be const or volatile, though a reference can refer to an entity that is const or volatile. An attempt to declare a reference const or volatile directly is an error:

int &const cri = a; // should be an error . . . 
const int &rci = a; // OK

Strangely, it's not illegal to apply a const or volatile qualifier to a type name that is of reference type. Rather than cause an error, in this case the qualifier is ignored:

typedef int *PI; 
typedef int &RI;
const PI p = 0; // const pointer
const RI r = a; // just a reference!

There are no null references, and there are no references to void:

C *p = 0; // a null pointer 
C &rC = *p; // undefined behavior
extern void &rv; // error!
原文地址:https://www.cnblogs.com/secbook/p/2655487.html