【问题标题】:Changing global variables in functions更改函数中的全局变量
【发布时间】:2015-04-21 09:53:56
【问题描述】:

我正在通过《从游戏开发开始 C++ 课程》这本书来学习 C++。

当我声明一个全局变量时,这个全局变量是不可更改的。当我在函数中声明一个局部变量时,它应该简单地隐藏全局变量。问题是,在函数中声明局部变量时,我似乎正在更改全局变量。以下代码将帮助我解释:

//the code
// ConsoleApplication64.cpp : Defines the entry point for the console     application.
//

#include <iostream>
#include <string>

using namespace std;

int glob = 10; //The global variable named glob
void access_global();
void hide_global();
void change_global();

int main()
{
cout << "In main glob is: " << glob << endl;
access_global();

cout << "In main glob is: " << glob << endl;
hide_global();

cout << "In main glob is: " << glob << endl;
change_global();
cout << "In main glob is: " << glob << endl;

system("pause");
return 0;
}

void access_global(){
cout << "In access global is: " << glob << endl;
}

void hide_global(){
glob = 0;
cout << "In hide global is: " << glob << endl;
}

void change_global(){
glob = 5;
cout << "In change global is: " << glob << endl;
} 

当我第一次在 int main 中计算 glob 时,它具有全局值 10。然后我在函数中计算 glob,它似乎工作正常,5。然后我想再次在 main 中计算 glob,只有找出值已从全局的 10 变为本地的 5。这是为什么?根据这本书,这不应该发生。我在 Microsoft Visual Studio 2010 工作。

【问题讨论】:

  • 这段代码中没有局部变量。仔细阅读声明。
  • “我正在学习 c++……当我声明一个全局变量时……” - 停止!
  • @Component10 来吧...学习 C++ 的一部分是了解命名空间范围变量的规则。这显然不是真实项目中的代码。
  • @PaulMcKenzie 这与其他语言有什么关系?他只是在学习 C++ 中的一个特定概念。
  • @Component10 我只是在学习这些东西,兄弟。但现在我很感兴趣。为什么我永远不能声明全局变量?

标签: c++ function variables global local


【解决方案1】:

代码:

void hide_global(){
glob = 0;
cout << "In hide global is: " << glob << endl;
}

没有声明任何新变量,它分配给一个名为glob已经存在变量,这是您的全局变量。要在函数中声明一个新变量,您还需要指定数据类型,如下所示:

void hide_global(){
int glob = 0;
cout << "In hide global is: " << glob << endl;
}

【讨论】:

    【解决方案2】:

    您没有在任何hide_global 函数中创建局部变量,您只是在更改全局变量。要创建新的本地版本,请执行以下操作:

    void hide_global(){
        int glob = 0; //note the inclusion of the type to declare a new variable
        cout << "In hide global is: " << glob << endl;
    }
    

    【讨论】:

      【解决方案3】:
      void hide_global(){
        glob = 0;
        cout << "In hide global is: " << glob << endl;
      }
      

      您根本没有在这里隐藏全局变量。您只是将 0 分配给全局变量。事实上,它与您的 change_global 函数完全相同 - 那么您为什么希望它的行为有所不同呢?

      要隐藏变量,您需要声明一个新变量。变量声明由类型、名称和可选的初始化程序组成。对于您的代码,它看起来像这样:

      void hide_global(){
        int glob = 0;
        cout << "In hide global is: " << glob << endl;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-04
        • 1970-01-01
        • 2014-09-06
        • 1970-01-01
        • 2013-03-14
        相关资源
        最近更新 更多