通过引用和全局变量传递

Pass by reference and global variables

我正在学习函数、引用和全局变量。 我有以下代码:

    #include <iostream>
    using namespace std;

    int x;
    void f(){ x = 2;}
    
    void g(int &x){ f(); }

    int main() {
        int x=5;
        g(x);
        cout<<x;
    }

为什么我没有得到 2 作为输出?由于 x 在 g() 内部发生变化,我希望保留该值。

函数void f()作用于全局x。传递给 void g(int&) 的参数未被使用。

全局 xmain() 中定义的 automatic x 隐藏

std::cout << "local " << x << " global " << ::x;

看看这两个变量会发生什么。

如果我们在 C++ 中有同名的局部变量,我们可以使用作用域解析运算符访问全局变量 (::)

在你的主要功能中你只需要使用cout<<::x;

为了更好的理解,请看下面的简单代码或者参考这个link

How to access a global variable within a local scope?

#include <iostream>
using namespace std;
 
int x = 5;     // Global x 
int main()
{
    int x = 2; // Local x
    cout << "Value of global x is " << ::x << endl;
    cout << "Value of local x is " << x;
    getchar();
    return 0;
}