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;

}

运行结果:
运行结果

原创文章 44 获赞 8 访问量 3886

猜你喜欢

转载自blog.csdn.net/weixin_44692299/article/details/104277929