码迷,mamicode.com
首页 > 编程语言 > 详细

c++的引用

时间:2015-10-03 11:55:35      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

假如定义了某个变量的别名,该别名就永远属于这个变量,它是某个变量的别名的这个身份我们无法更改,但是我们可以更改它所引用的值

定义引用的时候一定要记得对该引用进行初始化,引用就是常量,我们只能对它初始化,不能赋值,

下面用代码演示上述语句

#include <iostream>
using namespace std;
int main()
{
    int a;
    int &ra = a;
    a = 999;
    cout << "&a:\t" << &a << endl;
    cout << "&ra:\t" << &ra << endl;
    cout << "\n";
    int b = 888;
    ra = b;
    cout << "&a:\t" << &a << endl;
    cout << "&ra:\t" << &ra << endl;
    cout << "&b:\t" << &b << endl;
    cout << "a:\t" << a << endl;
    cout << "ra:\t" << ra << endl;
    cout << "b:\t" << b << endl;
    cout << "\n";
    ra = 1;
    cout << "&a:\t" << &a << endl;
    cout << "&ra:\t" << &ra << endl;
    cout << "&b:\t" << &b << endl;
    cout << "a:\t" << a << endl;
    cout << "ra:\t" << ra << endl;
    cout << "b:\t" << b << endl;
    return 0;
}

 当然也可以定义对象的别名,代码如下:

/*定义对象的别名*/
#include <iostream>
using namespace std;
class Human
{
public:
    int get() {return i;}
    void set(int x) {i = x;}
private:
    int i;
};
int main()
{
    Human Mike;
    Human &rMike = Mike;
    rMike.set(111);
    cout << "Mike:" << Mike.get() << endl;
    cout << "rMike:" << rMike.get() << endl;
    return 0;
}

 

c++的引用

标签:

原文地址:http://www.cnblogs.com/rain-1/p/4853196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!