引用(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!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值