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

本文详细介绍了C++程序中命名空间的使用细节,包括命名空间的定义、作用域、作用方式以及如何在代码中声明和使用命名空间中的元素。通过具体的示例,展示了如何在不同命名空间中组织代码,避免名称冲突,提高代码的可读性和可维护性。

用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() << '\n';
    cout << bar::value() << '\n';
    cout << bar::pi << '\n';
    
    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 << '\n';
    cout << y << '\n';
    
    // 直接使用命名空间中的某个元素
    cout << first::y << '\n';
    cout << second::x << '\n';
    
    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 << '\n';
    cout << y << '\n';
    
    // 使用命名空间second中的元素
    cout << second::x << '\n';
    cout << second::y << '\n';
    
    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 << '\n';
    }
    
    // 使用命名空间second
    {
        using namespace second;
        cout << x << '\n';
    }
    
    return 0;
}

打印结果

5
3.1416
Program ended with exit code: 0

 

转载于:https://www.cnblogs.com/YouXianMing/p/4322958.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值