9.1 使用引用(引用就是别名,声明引用时必须初始化)

Posted: March 26, 2011 in C++

/*
引用就是别名.
创建时,将其初始化为另一个对象(即目标)的名称.
然后,引用将成为目标的另一个名称,对引用执行的任何操作实际上都是 针对 目标的;

语法:类型 &r引用名 = 目标名 (r提醒是引用名,可省略)

比如:
President George_Washington;
引用:
President &rFatherOfCountry = George_Washington;
所以,针对引用名做出的任何操作实际上也就是针对目标名的,只是别名而已.

声明引用时必须初始化.
*/

#include <iostream>
using namespace std;

void main()
{
           int number=5;
           int &rNumber=number;

           cout<<rNumber<<endl;
 
           //而修改别名的值,同时也就是修改目标名的值
           rNumber=10;
           cout<<number<<endl;

           //内存的储存是否一样?查看它的内存地址是否一样.
           cout<<&number<<endl;
           cout<<&rNumber<<endl;
 
 
           //可能你会想能否给引用重新赋值呢?
           int NewNumber=100;
           rNumber=NewNumber;
           cout<<number<<endl;
           cout<<rNumber<<endl;
           cout<<NewNumber<<endl;
 
           /*你会发现所有值都变成了100,实际上rNumber仍旧是number的别名.
           可以等价于:
           number=NewNumber;
          所以number的值也变成了100.因而不能给引用重新赋值.*/
 
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s