reference 返回值问题

201 阅读1分钟

如果返回的是refenrece 接收也需要是reference才能改变所指向的值。否则发生的还是值拷贝。同理,map中的reference返回值也需要是reference接收才能直接改动。

int& re(int& x){
	x=x+1;
	return x;

}
int main() {
	int x = 2;
	int& b = re(x);
	cout << b << endl;
	cout << x << endl;
	b++;
	cout << x << endl;
	return 0;

}

image.png

int& re(int& x){
	x=x+1;
	return x;

}
int main() {
	int x = 2;
	int b = re(x);
	cout << b << endl;
	cout << x << endl;
	b++;
	cout << x << endl;
	return 0;

}

image.png