面试题
题目
#include <iostream>
using namespace std;
int a = 4;
int &f(int x){
a = a+x;
return a;
}
int main()
{
int t = 5;
cout << f(t)<<endl; // 输出结果为:?
f(t) = 20;
cout << f(t)<<endl; // 输出结果为:?
t = f(t);
cout << f(t)<<endl; // 输出结果为:?
return 0;
}
答案
9
25
60
分析
#include <iostream>
using namespace std;
int a = 4; // 全局变量
int &f(int x){ // 调用函数时,返回的是a的地址
a = a+x;
return a;
}
int main()
{
int t = 5;
// t=5;a=4;
cout << f(t)<<endl;
// a = a+x = 4+5 = 9;
// f(t)=9
// 输出结果为:9
/****************************/
f(t) = 20;
// t=5; a=9;
// a = a+x = 9+5 = 14;
// 此时 f(t)引用a的地址,f(t)=20; 则a的值被修改为20
cout << f(t)<<endl;
// a = a+x = 20+5 = 25;
// f(t)=25
// 输出结果为:25
/****************************/
t = f(t);
// t=5; a=25;
// a = a+x = 25+5 = 30;
// t = f(t) = 30;
cout << f(t)<<endl;
// a = a+x = 30+30 = 60;
// f(t)=60
// 输出结果为:60
return 0;
}
知识点
参考资料