c ++ Scope

Scope

A scope is a valid identifier in the program area of ​​the body

1. Function prototype scope

函数作用域是C++程序中最小的作用域,在函数原型声明时参数的作用范围就是函数原型的作用域

2. Local Scope

函数体内声明的变量,其作用域从声明处开始,一直到声明所在的块结束的大括号为止,局部变量的作用范围便是局部作用域。

3. class scope

类可以被看做是一组有名成员的集合,类的成员m具有类作用域,对m的访问有三种:

(1) If there is no statement in the member function of the same name in the local scope identifiers X, then the function in the direct access members m. In other words such a function m are functional.
(2) or by the expression xm x :: m. This is the most basic way to access object members of the program.
(3) By ptr-> such expressions m, wherein ptr to point to a pointer to the class object x.

4. namespace scope

一个大型的程序通常)模块构成 .不同的模块甚至有可能 是由不同人员开 发的。不同模块 中的类和丽数可能发生重名。这样就会引发错误。 这就好像上海和武汉都有南京路,如果在缺乏k的情况下直接说出“南京路”,就会产生歧义。但如果说“上海的南京路”或武汉的”,歧义就会消除。命名空间起到的就是这样的作用。命名空间的语法形式如下:
    namespace 命名空间名
{
    命名空间内的各种声明(函数声明、类声明、......)
}

A domain name to identify a namespace declaration in the space belong to the domain name space, but want to use identifiers other spaces, use the following syntax:
namespace identifier name name ::

Scope Example:

    #include <iostream>
    using namespace std;
    int i;//在全局命名空间中的全局变位
    namespace Ns 
    {
        int j;//在N命名空间中的全局变量
    }
    int main()
    {
    i=5; //为全局变量 i 赋值
    Ns::j=6;//为全局变量 j 赋值
    {
        using namespace Ns;//使得在当前块中可以直接引用Ns命名空间的标识符
        int i;//局部变量,局部作用域
        i=7;
        cout<<"i="<<i<<endl; //输出 7
        cout<<"j="<<j<<endl; //输出6
    }
       cout<<"i="<< i<< endl;//输出5
        return 0;
    }

Run Results:

In this example, the variable i has namespace City effect, it belongs to the global namespace, its effective scope to the end of the file until the end. In the beginning of the main function to the namespace variables having the same initial value scope 5. Next, in sub-block 1 and the same variables are declared and the initial value 7. The first result is output 7. This is because the local scope of the variables the variable i with i namespace scope hides, having a variable namespace scope of i, becomes invisible (which is discussed below the visibility problem). When the program runs to the end of the block 1, a second output, the output is a variable having the same scope namespace value i 5. Variable j have namespace scope, it is declared in the namespace Ns by Ns :: j of reference in the main function, assign it, then in block 1, such that by using namespace Ns namespace the identifier may be referenced directly in that block, using the identifier can be directly output j j.

Guess you like

Origin www.cnblogs.com/yygxy/p/11592831.html