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
  • 相关阅读:
    人事不干人事,这算什么事
    java 单例模式
    Java 中类的加载顺序
    新的挑战
    读《月亮和六便士》所思
    读《奇特的一生》后的一些感悟
    BTrace
    Java技能树
    Android Intent
    一个ListView优化的例子
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/4322958.html
Copyright © 2011-2022 走看看