c++引用

#include<iostream.h>
using namespace std;

int & getInt();

int main(){
	int & rInt = getInt();
	cout<<"rInt is: "<<rInt<<endl;
	return 0;
}

int & getInt(){
	int localVar = 25;
	return localVar;  // localVar为局部变量   在函数返回时localVar变量将被销毁,所以返回的引用是不存在的变量的别名
}

/**
 * 如果被引用的对象可能位于作用域外,不要按引用传递
 * 不用失去内存是何时在什么地方分配的线索,以确保内存得到释放。
 *
 * rInt is: 25
 * */

猜你喜欢

转载自abc20899.iteye.com/blog/1873370