zoukankan      html  css  js  c++  java
  • C++命名空间namespace

    作用:避免变量或函数的命名冲突 

    定义:

    namespace 名字空间名{

    名字空间成员1;

    名字空间成员1;

    ......

    }

    注意:名字空间成员可以是全局函数、全局变量、类型、名字空间

    实例

    #include <iostream>
    
    namespace ns1 {
        void func() {
            std::cout << "ns1的func" << std::endl;
        }
    }
    namespace ns2 {
        void func() {
            std::cout << "ns2的func" << std::endl;
        }
    }
    
    
    
    int main()
    {
        //func();   不能直接访问
        ns1::func();
        ns2::func();
      
        
    
        system("pause");  //暂停
    }
    using namespace 名字空间名
    #include <iostream>
    
    
    
    namespace ns1 {
        void func() {
            std::cout << "ns1的func" << std::endl;
        }
    }
    namespace ns2 {
        void func() {
            std::cout << "ns2的func" << std::endl;
        }
    }
    
    
    
    int main()
    {
        using namespace ns1;
        func();  //可以省略ns1::
        ns2::func();
      
        
    
        system("pause");  //暂停
    }
    #include <iostream>
    
    namespace ns1 {
        void func() {
            std::cout << "ns1的func" << std::endl;
        }
    }
    namespace ns2 {
        void func() {
            std::cout << "ns2的func" << std::endl;
        }
    }
    
    
    
    int main()
    {
        using  ns1::func;
        func();  //可以省略ns1::
        ns2::func();
         
    
        system("pause");  //暂停
    }
    #include <iostream>
    
    namespace ns1 {
        void func() {
            std::cout << "ns1的func" << std::endl;
        }
    }
    namespace ns2 {
        void func() {
            std::cout << "ns2的func" << std::endl;
        }
    }
    
    
    
    int main()
    {
        using  ns1::func;  //声明方法一
        using namespace ns2;  //声明方法二
        func();  //执行的是ns1的func
        //以声明方法一为主
    
    
        system("pause");  //暂停
    }

    名字空间的嵌套

    #include <iostream>
    
    namespace ns1 {
        int num = 100;
            namespace ns2 {
                int num = 200;
                namespace ns3 {
                    int num = 300;
                }
        }
    }
    
    int main()
    {
        std::cout << ns1::ns2::num << std::endl;  //输出值200
        
        system("pause");  //暂停
    }

    名字空间的合并

    两个同名空间会自动合并,但两个空间中不能有同名成员或函数

    #include <iostream>
    
    namespace ns1 {
        int unm = 100;
    }
    namespace ns1 {
        int unm1 = 200;
    }
    
    int main()
    {
        std::cout << ns1::unm << std::endl;
        std::cout << ns1::unm1 << std::endl;
        
        system("pause");  //暂停
    }

  • 相关阅读:
    模板模式创建一个poi导出功能
    vim python和golang开发环境配置
    vim快捷键
    golang聊天室
    goroutine与channels
    Redis中的GETBIT和SETBIT(转载)
    二叉树
    满二叉树与完全二叉树
    拓扑排序
    ZigZag Conversion
  • 原文地址:https://www.cnblogs.com/liming19680104/p/14830494.html
Copyright © 2011-2022 走看看