我看大学里很少有关于C++的练习,我发现了这个练习:
#include <iostream>
using namespace std;
int x = -2;
int h(int &x) {
x = 2 * x;
return x;
}
int g(int f) {
return x;
}
int &f(int &x) {
x += ::x;
return x;
}
int main() {
int x = 6;
f(::x) = h(x);
cout << f(x) << endl;
cout << g(x) << endl;
cout << h(x) << endl;
return 0;
}此代码的输出是:
24
12
48有人能解释一下我怎么得到这个输出吗?
f(::x) = h(x);是如何工作的呢?
发布于 2015-12-20 17:11:25
还记得局部变量隐藏全局变量吗?你在这里所拥有的就是这一原则。
考虑函数
int &f(int &x) {
x += ::x;
return x;
}在这里,作为参数传递的int &x是函数的本地变量;其中函数中的::x引用全局变量x。
顺便说一句,::被称为范围解析操作符,在C++中也用于许多其他用途。
https://stackoverflow.com/questions/34383098
复制相似问题