C++中引用变量的用例
#include<iostream>
using namespace std;
int main()
{
int i = 1;
int &x = i; // 对变量I的引用
cout<<"i = "<<i<<" "<<"address = "<<&i<<endl;
cout<<"x = "<<x<<" "<<"address = "<<&x<<endl;
int y = 2;
x = y;
cout<<"i = "<<i<<" "<<"address = "<<&i<<endl;
cout<<"x = "<<x<<" "<<"address = "<<&x<<endl;
cout<<"y = "<<y<<" "<<"address = "<<&y<<endl;
return 0;
}
结果如下using namespace std;
int main()
{
int i = 1;
int &x = i; // 对变量I的引用
cout<<"i = "<<i<<" "<<"address = "<<&i<<endl;
cout<<"x = "<<x<<" "<<"address = "<<&x<<endl;
int y = 2;
x = y;
cout<<"i = "<<i<<" "<<"address = "<<&i<<endl;
cout<<"x = "<<x<<" "<<"address = "<<&x<<endl;
cout<<"y = "<<y<<" "<<"address = "<<&y<<endl;
return 0;
}
i = 1 address = 0012ff6c
x= 1 address = 0012ff6c
i = 2 address = 0012ff6c
x= 2 address = 0012ff6c
y= 2address = 0012ff70
作为i的引用x,它们都指向相同的值和地址.
x=y;只是改变x的值,由于x是i的引用,所以,不能改变x的地址