更改函数中的全局变量

Ste*_*hen 2 c++ variables global function local

我正在通过《通过游戏开发从 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;
} 
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*sen 5

代码:

void hide_global(){
glob = 0;
cout << "In hide global is: " << glob << endl;
}
Run Code Online (Sandbox Code Playgroud)

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

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