【问题标题】:Function giving precedence to GLOBAL variable instead of LOCAL - (Anomalous behaviour)优先于 GLOBAL 变量而不是 LOCAL 的函数 - (异常行为)
【发布时间】:2020-01-07 17:02:32
【问题描述】:

我有:

  1. string s = "global" [全局范围]
  2. string s = "local" [局部作用域(主函数)]

我希望函数f1() 在从main 调用时打印出本地s,但该函数正在打印全局s

#include <iostream>
using namespace std;

//global variables & functions .h

string s = "global";    void f1();

//main begins
int main()
{
    string s = "local";
    f1();

    return 0;
}

//function definitions .cpp

void f1()
{
    cout << s;
}

输出是:

global
Process returned 0 (0x0)   execution time : 0.281 s
Press any key to continue.

【问题讨论】:

  • 问问自己,f1 应该如何看到 main 本地的 s
  • f1 不知道main 中的本地s,只看到全局s。如果您希望f1 了解 main 的 s,您需要将其作为参数传递。
  • 你在用哪本书来学习 C++?
  • 查看 question 以更广泛地讨论名称范围。
  • f1() 应该看到本地的 s 因为std::cout 也看到了它。 例如如果我在 main 中输入std::cout &lt;&lt; s;,那么它将输出local。那么问题来了,为什么f1() 没有表现出相同的行为?是不是因为std::cout的执行?如果有人能阐明这一点,那将非常有用。

标签: c++ function scope global-variables


【解决方案1】:

这是因为全局定义是f1 唯一可见的定义。这是 lexicaldynamic 作用域之间的区别,我建议您查看其定义。 C++ 是 lexically 范围的,这意味着它只能根据相对于代码的定义位置来查看符号。 f1 只能看到其中定义的局部变量,而全局变量,它甚至不知道main 中的变量存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多