C++返回引用的函数中遇到的问题

C++语言 码拜 8年前 (2016-04-03) 1167次浏览
#include<bits/stdc++.h>
using namespace std;
int &Max(int &a,int &b)
{
	return a>b?a:b;
}
int main()
{
    ios::sync_with_stdio(false);
	int a,b;
	a=2,b=1;
	int c=Max(a,b);
	c=0;
	cout<<&a<<endl;
	cout<<&c<<endl;
	cout<<&Max(a,b)<<endl;
    return 0;
}

上面代码输出的地址第第一个和第三个相同

#include<bits/stdc++.h>
using namespace std;
int &Max(int &a,int &b)
{
	return a>b?a:b;
}
int main()
{
    ios::sync_with_stdio(false);
	int a,b;
	a=2,b=1;
	int &c=Max(a,b);
	c=0;
	cout<<&a<<endl;
	cout<<&c<<endl;
	cout<<&Max(a,b)<<endl;
    return 0;
}

当把c改成引用时,输出的地址第一个和第二个相同。和第三个不同,是怎么回事呢?

解决方案

10

#include<bits/stdc++.h>
using namespace std;
int &Max(int &a,int &b)
{
	return a>b?a:b;
}
int main()
{
    ios::sync_with_stdio(false);
	int a,b;
	a=2,b=1;
	int &c=Max(a,b); // 这里 Max 返回a,c 是 a 的引用
	c=0; // c 是 a 的引用,所以这句之后, a == c == 0 。
	cout<<&a<<endl;
	cout<<&c<<endl;
	cout<<&Max(a,b)<<endl; // a == 0, b == 1, 这时 Max 返回的 b 而不是 a
    return 0;
}

当把c改成引用时,输出的地址第一个和第二个相同。和第三个不同,是怎么回事呢?

20

c=0; 这句使得a也变成了0
所以Max返回的结果是b的地址
题主可测试b的地址,看能否相等

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++返回引用的函数中遇到的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)