gpt4 book ai didi

c++ - C++ 中的全局变量和局部变量

转载 作者:太空狗 更新时间:2023-10-29 20:52:24 25 4
gpt4 key购买 nike

我是 C++ 的新手,在打印局部变量和全局变量时遇到了一些问题。考虑这段简单的代码:

#include <cstdlib>
#include <iostream>

using namespace std;

/*
*
*/
int x = 10; // This x is global
int main() {
int n;
{ // The pair of braces introduces a scope
int m = 10; // The variable m is only accessible within the scope
cout << m << "\n";

int x = 25; // This local variable x hides the global x
int y = ::x; // y = 10, ::x refers to the global variable x
cout << "Global: " << y << "\n" << "Local: " << x << "\n";
{
int z = x; // z = 25; x is taken from the previous scope
int x = 28; // it hides local variable x = 25 above
int t = ::x; // t = 10, ::x refers to the global variable x
cout << "(in scope, before assignment) t = " << t << "\n";
t = x; // t = 38, treated as a local variableout was not declared in this scope
cout << "This is another hidden scope! \n";
cout << "z = " << z << "\n";
cout << "x = " << x << "\n";
cout << "(in scope, after re assignment) t = " << t << "\n";
}
int z = x; // z = 25, has the same scope as y
cout << "Same scope of y. Look at code! z = " << z;
}
//i = m; // Gives an error, since m is only accessible WITHIN the scope

int m = 20; // This is OK, since it defines a NEW VARIABLE m
cout << m;

return 0;
}

我的目标是练习变量在各种范围内的可访问性,然后打印它们。但是,我无法弄清楚为什么当我尝试打印最后一个变量 z 时,NetBeans 返回输出 2025。这是我的示例输出:

10
Global: 10
Local: 25
(in scope, before assignment) t = 10
This is another hidden scope!
z = 25
x = 28
(in scope, after re assignment) t = 28
Same scope of y. Look at code! z = 2520
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms

希望有人能帮助我理解发生了什么! :)

最佳答案

不是 z 持有值 2520 是您在打印 z 和打印之间添加新行运算符的事实m...

你在做什么:

cout << "Same scope of y. Look at code! z = " << z;
}

int m = 20;
cout << m;

但是你应该这样做:

std::cout << "Same scope of y. Look at code! z = " << z << std::endl;
}

int m = 20;
std::cout << m << std::endl;

如果您只是遵循相同的标准来标记输出并执行类似的操作

std::cout << "M is: "<<m << std::endl;

您可以通过观察输出更快地发现问题:

25M is: 20 

关于c++ - C++ 中的全局变量和局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com