[C++] 引用

#include<iostream>
using namespace std;

int main(){
	int i = 20;
	int j = 40;
	int & a = i;
	int & b = i;
	//int & c = i*2; //error reference 不能用右值赋值
	int const & c = i*2;//绑定临时变量 

	cout<<" a: "<<a<<" b: "<<b<<" c: "<<c<<endl;
	cout<<" &i: "<<&i<<" &j: "<<&j<<endl;
	cout<<" &a: "<<&a<<" &b: "<<&b<<" &c: "<<&c<<endl;
	a = 30;
	b = j;//j 值传递,转换成右值,下同
	//c = i; error: assignment of read-only reference 'c'
	//c = 30;error read only
	cout<<" a: "<<a<<" b: "<<b<<" c: "<<c<<endl;
	cout<<" &i: "<<&i<<" &j: "<<&j<<endl;
	cout<<" &a: "<<&a<<" &b: "<<&b<<" &c: "<<&c<<endl;
	return 0;
}
posted @ 2018-08-06 16:32  zengzhaocheng  阅读(82)  评论(0编辑  收藏  举报