[英]Changing global variables in functions
我正在學習“通過游戲開發從入門開始學習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中工作。
您沒有在任何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;
}
編碼:
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;
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.