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
  • 相关阅读:
    webpack 中级配置
    webpack4学习笔记
    window搭建go环境
    谈谈你对laravel的契约,容器,服务提供者,facades的理解以及他们的关系是什么
    php开发微信公众号踩坑
    腾讯云搭建git服务器
    linux的常用命令
    egg项目部署
    axios的使用记录以及实现上传图片
    SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/4322958.html
Copyright © 2011-2022 走看看