C ++中的可变范围? [英] Variable Scope in C++?
问题描述
在c ++中,main中声明的任何变量在整个main权限中都可用吗?我的意思是,如果变量在try循环中声明,它们在整个main中是否仍可访问?因为我在main的try循环中声明了几个变量,但是如果在try循环之外的main的任何其他部分中使用它们,则会收到在此范围内未声明"错误
In c++, any variables declared in main will be available throughout main right? I mean if the variables were declared in a try loop, will they would still be accessible throughout main? Because I have declared several variables in a try loop in main, but if I use them in any other part of main outside the try loop, I get a "was not declared in this scope" error
很遗憾,我无法发布我的实际代码,但这基本上就是我正在做的事情
I unfortunately can't post my actual code but this is basically what I am doing
int main()
{
try
{
int number = 0;
}
catch (...)
{
cout <<"Error";
}
number ++;
cout <<number;
return 0;
}
我基本上会在第13和14行得到一个错误,说没有在此范围内声明数字.
I would basically get an error on line 13 and 14 saying number wasn't declared in this scope.
推荐答案
number
的范围仅限于 try
块.将该声明拉出到 main
范围,以在 try
块之后访问变量:
The scope of number
is limited to the try
block. Pull out this declaration to the main
scope to access the variable after the try
block:
int main()
{
int number = 0;
try
{
// do something...
}
catch (...)
{
cout <<"Error";
}
number ++;
cout <<number;
return 0;
}
这篇关于C ++中的可变范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!