• 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 << "
    B::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 << "
    test2:" << endl;
        printf("C::int_a = %d
    C::D::int_a = %d
    ",C::int_a,C::D::int_a);
    }
    
    // 命名空间是开放的,可以随时添加新成员
    // 同名的命名空间做 合并操作
    namespace C
    {
        char char_a = 'C';
        void t();
    }
    
    void C::t()
    {
        // ...
    }
    
    void test3(void)
    {
        cout << "
    test3:" << endl;
        cout << "C::char_a = " << C::char_a << endl;
    }
    
    // 命名空间可以匿名
    namespace
    {
        int quanju = 0; // 命名空间是匿名时 变量前隐式添加了关键字static,相当于全局变量
    }
    
    void test4(void)
    {
        cout << "
    test4:" << endl;
        cout << quanju << endl;
    }
    
    // 命名空间可以起别名
    namespace long_long_name
    {
        int a = 0;
    }
    
    void test5(void)
    {
        namespace short_name = long_long_name;
        cout << "
    test5:" << 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
    
  • 相关阅读:
    info plist各个功能的详解
    打个测试包弄成连接供别人下载测试
    封装的数据请求加上风火轮的效果
    福大软工 · BETA 版冲刺前准备(团队)
    福大软工 · 第十一次作业
    Alpha 冲刺 (10/10)
    Alpha 冲刺 (9/10)
    Alpha 冲刺 (8/10)
    Alpha 冲刺 (7/10)
    Alpha 冲刺 (6/10)
  • 原文地址:https://www.cnblogs.com/zhujiangyu/p/13866294.html
Copyright © 2020-2023  润新知