注册 登录
编程论坛 C++教室

理解作用域示例

hmsabc 发布于 2010-08-19 10:26, 549 次点击
程序代码:
//作用域问题

#include <iostream>
using namespace std;

int main( )
{
int count1 = 10;
int count3 = 50;
cout << endl
<< "Value of outer count1 = " << count1
<< endl;
{
    int count1 = 20;                                    //此为内部变量 count1
    int count2 = 30;                                    //此为内部变量 count2
    cout << "Value of inner count1 = " << count1
        << endl;
    count1 += 3;                                         //此处的运算是内部运算
    cout << "My count1 = " << count1 << endl;            //输出内部运算的值 23
    count3 += count2;                                    //此 count3 是在外部定义的,属全局变量,count 2 为局部变量
}
cout << "Value of outer count1 = " << count1             //此处输出的仍然是全局变量的 count1
<< endl
<<"Value of outer count3 = " << count3                   //此处输出的是全局变量的 count3 已经在原始值上加了 30
<< endl;
system("pause");

return 0;
}
3 回复
#2
zhoufeng19882010-08-19 10:35
main函数域中的count1和count3可不是全局变量哦~
全局变量是你的整个程序中都是有效可访问的,而main函数中的count1和count3只有在main函数可见。
#3
hmsabc2010-08-19 14:28
回复 2楼 zhoufeng1988
知道了,概念不清造成的,谢谢!
#4
holychild2010-08-23 15:26
全局变量不是在main函数里面定义的。
1