C++函数输出

C++ function output

我在大学里找了一些关于 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); 是如何工作的?

  1. ::x 指的是全局 int x,而不是局部 x.

    参见:What is the meaning of prepended double colon “::” to class name?

  2. 函数签名不同(按值或引用传递 x)。前者制作副本,后来 并且 int &x 上的更改将反映 x 所指的内容(您作为参数传递的内容)。

    参见:What's the difference between passing by reference vs. passing by value?

  3. 如果您将 int & 作为 return 类型,您将能够通过此引用对其进行更改 returns 以传递给 f(引用)。

考虑上述代码的工作原理。

还记得局部变量隐藏全局变量吗?您在这里看到的是该原则的实际应用。

考虑函数

int &f(int &x) {
    x += ::x; 
    return x;
}

这里 int &x 作为参数传递的是函数的局部参数;其中函数中的 ::x 指的是全局变量 x.

顺便说一下,:: 称为作用域解析运算符,在 C++ 中也用于许多其他目的。