标签:
假如定义了某个变量的别名,该别名就永远属于这个变量,它是某个变量的别名的这个身份我们无法更改,但是我们可以更改它所引用的值
定义引用的时候一定要记得对该引用进行初始化,引用就是常量,我们只能对它初始化,不能赋值,
下面用代码演示上述语句
#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; }
标签:
原文地址:http://www.cnblogs.com/rain-1/p/4853196.html