传递引用和全局变量



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

#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()中定义的自动x遮蔽。

写入

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

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

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

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

为了更好地理解,请参阅以下简单代码或参考此链接

如何访问本地范围内的全局变量?

#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;
}

最新更新