zoukankan      html  css  js  c++  java
  • [C++] 用Xcode来写C++程序[6] Name visibility

    用Xcode来写C++程序[6] Name visibility

    此小结包括了命名空间的一些使用细节

    命名空间

    #include <iostream>
    using namespace std;
    
    namespace foo {
        // 函数
        int value() {
            return 5;
        }
    }
    
    namespace bar {
        // 常量
        const double pi = 3.1416;
        
        // 函数
        double value() {
            return 2*pi;
        }
    }
    
    int main () {
        cout << foo::value() << '
    ';
        cout << bar::value() << '
    ';
        cout << bar::pi << '
    ';
        
        return 0;
    }

    打印结果

    5
    6.2832
    3.1416
    Program ended with exit code: 0

    使用命名空间

    #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 << '
    ';
        cout << y << '
    ';
        
        // 直接使用命名空间中的某个元素
        cout << first::y << '
    ';
        cout << second::x << '
    ';
        
        return 0;
    }

    打印结果

    5
    2.7183
    10
    3.1416
    Program ended with exit code: 0
    #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 () {
        // 声明使用命名空间first中的元素
        using namespace first;
        cout << x << '
    ';
        cout << y << '
    ';
        
        // 使用命名空间second中的元素
        cout << second::x << '
    ';
        cout << second::y << '
    ';
        
        return 0;
    }

    打印结果

    5
    2.7183
    10
    3.1416
    Program ended with exit code: 0
    #include <iostream>
    using namespace std;
    
    namespace first {
        int x = 5;
    }
    
    namespace second {
        double x = 3.1416;
    }
    
    int main () {
        // 使用命名空间first
        {
            using namespace first;
            cout << x << '
    ';
        }
        
        // 使用命名空间second
        {
            using namespace second;
            cout << x << '
    ';
        }
        
        return 0;
    }

    打印结果

    5
    3.1416
    Program ended with exit code: 0
  • 相关阅读:
    微信公众号自定义菜单创建方法
    Oracle数据库导入导出
    关于vs启动调试报错:CS0016: 未能写入输出文件“xxxxxxxx”--“目录名称无效。”解决方法
    Window Server 2012无线网卡和声卡驱动解决方法
    NodeJS下载文件实例
    MSSQL大全
    SQL函数介绍
    SQLite语法
    Curl简单使用
    Python中的argparse模块的使用
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/4322958.html
Copyright © 2011-2022 走看看