C++学习笔记3,namespace的使用

namespace的使用

1、命名空间必须定义在全局作用域下
2、命名空间下可以放函数、变量、结构体、类、可以嵌套命名空间
3、namespace命名空间的主要功能用来解决命名相同的冲突问题

4、命名空间是开放的,可以随时在原先命名空间添加内容,另起名后直接与原先的已有内容合并
5、namespace空间名可以起别名

#include "iostream"
using namespace std;

//test1命名空间
namespace test1{
    void test();
}
//test2命名空间
namespace test2{
    void test();
}
//1、namespace命名空间的主要功能用来解决命名相同的冲突问题
//2、命名空间必须定义在全局作用域下
//3、命名空间下可以放函数、变量、结构体、类、可以嵌套命名空间
namespace test3{
    void func();
    int a = 31;
    struct Person
    {

    };
    class Sex{};
    namespace test4{
        int a = 32;
    }
}
//4、命名空间是开放的,可以随时在原先命名空间添加内容
//此处test3空间名和上面的test3空间名进行合并
namespace test3{
    int b = 33;
}
//5、namespace空间名可以起别名
namespace veryLongName{
    int a = 666666666666666;
}

//test1函数调用test
void test1::test(){
    cout << "test1调用成功" << endl;
}
//test2函数调用test
void test2::test() {
    cout << "test2调用成功" << endl;
}

void testA (){
    cout <<"test3中的a = " << test3::a <<endl ;
    cout <<"test3下的test中的a = " << test3::test4::a <<endl ;

}
void testB(){
    cout <<"上面一个test3中的a = " << test3::a <<endl ;
    cout <<"下面一个test3中的b = " << test3::b <<endl ;
}
void testC(){
    //起别名
    namespace veryShortName = veryLongName;
    cout << "起别名前调用a,a =" <<veryLongName::a << endl;
    cout << "起别名后调用a,a =" <<veryShortName::a << endl;
}
int main()
{
    //在test1的命名空间下调用test
    test1::test();
    //在test2的命名空间下调用test
    test2::test();
    testA ();
    testB ();
    testC();
    return 0;

}

运行结果:
运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值