C++之作用域

分析一道题目:

#include <iostream>
using namespace std;
#include <cstdlib>

int count=3;//外部count

int main(int argc,char** argv)
{
    int i,sum,count=2;//main内count

    for(i=0,sum=0;i<count;i+=2,count++)//main内count
    {
        static int count=4;//static count
        count++; //static count

        if(i%2==0)
        {
            extern int count; //外部count
            count++; //外部count
            sum+=count;//外部count
        }
        sum+=count;//static count
    }
    printf("%d %d\n",count,sum);//main内count
    
    system("pause");
    return 0;
}

Key: 4,20

具体过程是这样的:

i=0:                                         i=2:        

    main内count=2,                           main内count=3,

    static count=5,                            static count=6,

    extern count=4,                           extern count=5,

    sum=4,                                       sum=14,

    sum=9;                                       sum=20;     main count=4.

当一个程序中出现多个同名变量时,作用域就开始显身手了。一般来说,最近原则:好比国家长官确实可以管理整个国家,但是某个地方的人民优先听从地方长官的命令,当地方长官不在时才会听从国家长官的命令。总体来说,main内的作用域是最近的花括号之内。

另一个例子:

#include <iostream>
#include <cstdlib>
using namespace std;

class X
{
public:
	X() 
	{
		cout << "X::X()\n";
	}
	~X()
	{
		cout << "X::~X()\n";
	}
};

X f1(X x1) //完全不使用引用
{
	cout << "f1(X f)\n";
	return x1;
}
X& f2(X& x2) //完全使用引用
{
	cout << "f2(X f)\n";
	return x2;
}

X Globle_X; //全局版本

int main()
{
	cout << "1--------\n";
	{
		X Local_X; //局部版本
		cout << "2--------\n";
	}
	cout << "3--------\n";
	X Normal_X;
	f1(Normal_X);
	cout << "-4-------\n";
	f2(Normal_X);
	cout << "---5-----\n";
	system("pause");
}

  关于代码注释中“完全不使用引用”和“完全使用引用”:

     称“完全不使用引用” 是因为这个更像是一个复制构造函数(引用是广义的),本质上是复制传值(对比结果看);

     称“完全使用引用”是因为这确实是引用(语言特性,指针间接指向,引用直接别名),更像一个带返回类型的函数。

结果:

2--------
X::~X()
3--------
X::X()
f1(X f)
X::~X()
X::~X()
-4-------
f2(X f)
---5-----

posted @ 2013-04-22 19:59  Tup  阅读(190)  评论(0)    收藏  举报