C++学习笔记之 命名空间

命名空间

#include <iostream>
#include <cstdio>

// using namespace std::cout; // 使用std中的cout
using namespace std; // 使用std中的所有定义

namespace A
{
    int a = 0;
}

namespace B
{
    int a = 10;
}

// 用途:解决名称冲突
void test1(void)
{
    cout << "test1:" << endl;
    cout << "A::a = " << A::a << "\nB::a = " << B::a << endl;
}

// 命名空间必须声明在全局作用域下
void test(void)
{
    // 局部作用域下不能定义命名空间
    //namespace _test
    //{
    //    int a = 0;
    //}
}

// 命名空间可以嵌套命名空间
namespace C
{
    int int_a = 0;
    namespace D
    {
        int int_a = 1;
    }
}

void test2(void)
{
    cout << "\ntest2:" << endl;
    printf("C::int_a = %d\nC::D::int_a = %d\n",C::int_a,C::D::int_a);
}

// 命名空间是开放的,可以随时添加新成员
// 同名的命名空间做 合并操作
namespace C
{
    char char_a = 'C';
    void t();
}

void C::t()
{
    // ...
}

void test3(void)
{
    cout << "\ntest3:" << endl;
    cout << "C::char_a = " << C::char_a << endl;
}

// 命名空间可以匿名
namespace
{
    int quanju = 0; // 命名空间是匿名时 变量前隐式添加了关键字static,相当于全局变量
}

void test4(void)
{
    cout << "\ntest4:" << endl;
    cout << quanju << endl;
}

// 命名空间可以起别名
namespace long_long_name
{
    int a = 0;
}

void test5(void)
{
    namespace short_name = long_long_name;
    cout << "\ntest5:" << endl;
    cout << short_name::a << endl;
}

int main(int argc, char *argv[])
{
    test1();
    test2();
    test3();
    test4();
    test5();

    return 0;
}

test1:
A::a = 0
B::a = 10

test2:
C::int_a = 0
C::D::int_a = 1

test3:
C::char_a = C

test4:
0

test5:
0
posted @ 2020-10-23 21:17  小宇宙zjy  阅读(88)  评论(0编辑  收藏  举报