如何使用 C++ 中的函数访问全局变量?

sah*_*ora 2 c++ global-variables scope-resolution-operator

我想从函数中访问分配给 main 函数中全局变量的值。我不想在函数中传递参数。

我曾尝试参考不同的堆栈溢出类似问题和 C++ 库。

#include <iostream>

long s;  // global value declaration

void output()  // don't want to pass argument
{
    std::cout << s;
}

int main()
{
    long s;
    std::cin >> s;  // let it be 5
    output()
}
Run Code Online (Sandbox Code Playgroud)

我希望输出是,5但它显示0.

Bat*_*ted 5

要访问全局变量,您应该::在它之前使用符号:

long s = 5;          //global value definition

int main()
{
    long s = 1;              //local value definition
    cout << ::s << endl;     // output is 5
    cout << s << endl;       // output is 1
}
Run Code Online (Sandbox Code Playgroud)

另外它是如此简单易用全球scin

cin >> ::s;
cout << ::s << endl;
Run Code Online (Sandbox Code Playgroud)

在线试用