当函数的返回值为引用时,不要返回局部变量的引用,可以返回全局变量的引用。

返回局部变量引用时,如果在函数外使用引用变量接收,会遇到它在栈上被释放的弊端。

int& getA(){
	int a=10;
	return a;
}
int main(){
	int &re = getA();
	cout<<re<<endl;
	cout<<"----------------------"<<endl;
	cout<<re<<endl;
}

猜你喜欢

转载自blog.csdn.net/qq_40945306/article/details/94547876