namespace关键字学习笔记

一、namespace简介

namespace中文意思是命名空间或者叫名字空间,传统的C++只有一个全局的namespace,但是由于现在的程序的规模越来越大,程序的分工越来越细,全局作用域变得越来越拥挤,每个人都可能使用相同的名字来实现不同的库,于是程序员在合并程序的时候就会可能出现名字的冲突。namespace允许像类,对象,函数聚集在一个名字下。本质上讲namespace是对全局作用域的细分。

二、namespace总结

1.namespace的格式基本格式

namespace identifier {
    entities;
}
eg:
namespace exp {
    int a,b;
}

2.在namespace外使用namespace内的变量需使用‘::’作用域描述符,eg:
exp::a
exp::b

3.使用namespace有效的避免重全局变量重定义

4.using关键字可以帮助从namespace中引入全局变量到当前的声明区域

eg:
#include <iostream>
using namespace std;

namespace first {
    int x = 5;
    int y = 10;
}

namespace second {
    double x = 3.1416;
    double y = 2.7183;
}

int main () {
    using first::x;
    using second::y;
    cout << x << endl;
    cout << y << endl;
    cout << first::y << endl;
    cout << second::x << endl;
    return 0;
}
输出是
5
2.7183
10
3.1416
就如我们所指定的第一个x是first::x,y是second.y

5.using关键字也可以导入整个的namespace

eg:
#include <iostream>
using namespace std;

namespace first {
    int x = 5;
    int y = 10;
}

namespace second {
    double x = 3.1416;
    double y = 2.7183;
}

int main () {
    using namespace first;
    cout << x << endl;
    cout << y << endl;
    cout << second::x << endl;
    cout << second::y << endl;
    return 0;
}
输出是
5
10
3.1416
2.7183

6.namespace的显示限定
在头文件中,我们通常坚持使用显式的限定,并且仅将using指令局限在很小的作用域中,这样他们的效用就会受到限制并且易于使用。

eg:
#include <iostream>
using namespace std;

namespace first {
  int x = 5;
}

namespace second {
  double x = 3.1416;
}

int main () {
    {
        using namespace first;
        cout << x << endl;
    }
    {
        using namespace second;
        cout << x << endl;
    }
    return 0;
}
输出是
5
3.1416

7.namespace支持嵌套
在namespace first中嵌套了namespace second,seond并不能直接使用,需要first来间接的使用。

eg:
#include <iostream>
namespace first {
    int a=10;
    int b=20;

    namespace second {   
        double a=1.02;
        double b=5.002;
        void hello();
    }   

    void second::hello() {   
        std::cout <<"hello world"<<std::endl;
    }
}

int main() {
    using namespace first;
    std::cout<<second::a<<std::endl;
    second::hello();
}
输出是
1.02
hello world

8.namespace可以使用别名

在对一些名字比较长的namespace使用别名的话,是一件很惬意的事。但是与using相同,最好避免在头文件使用namespace的别名(t比telephone更容易产生冲突)。
namespace t = telephone;

9.namespace提供了单独的作用域
它类似于静态全局声明的使用,可以使用未命名的namespace定义来实现

#include <iostream>

namespace {
    int count = 0;
}

void chg_cnt (int i) { 
    count = i; 
} 

int main () {

    count = 10;
    std::cout<<count<<std::endl; //没有指定using namespace std,而cout是std中定义的,因此要加上::
    return 0;
}

10. 一个例子: 一个源文件中有两个main()

#include <iostream>

using namespace std;

namespace android {
    int main(void)
    {
        cout << "android::main()" << endl;
        return 0;
    }

}

int main(void)
{

    cout << "std::main()" << endl;

    android::main();
    
    return 0;
}
原文地址:https://www.cnblogs.com/hellokitty2/p/10405808.html