:: namespace using作用

::

代表作用域 如果前面什么都不加 代表全局作用域

例如:如下的std::cout代表的是全局作用域中的std作用域

#include<iostream>
int a=100;

void func(int* x)
{
    int* b = &a;
    *x = a;
    std::cout <<"x:"<< x<<std::endl;
    std::cout << "*x:" << *x << std::endl;
}

int main()
{
    int b = 20;
    int* c = &b;
    func(c);
    std::cout << c << std::endl;
    std::cout << *c << std::endl;
}

namespace

可以用来解决名称冲突

namespace A
{
    using namespace std;
    void func1()
    {
        std::cout << "I'm A" <<  endl;
    }
    
}

namespace B
{
    using namespace std;
    void func1()
    {
        cout << "I'm B" << endl;
    }
}
void func2()
{
    A::func1();
    B::func1();
}

 

 

 

 

 

 命名空间可以存放变量、函数、结构体、类等,可以嵌套命名空间

namespace C
{
    using namespace std;
    int A_a = 10;
    namespace CB
    {
        int A_a = 20;
    }
    void func1()
    {
        cout << "A_a:" << A_a << endl;
        cout << "CB::A_a:" << CB::A_a << endl;
    }
}

 

 

 命名空间是开放的,可以随时将新成员添加到命名空间下

namespace C
{
    using namespace std;
    int A_a = 10;
    namespace CB
    {
        int A_a = 20;
    }
    void func1()
    {
        cout << "A_a:" << A_a << endl;
        cout << "CB::A_a:" << CB::A_a << endl;
    }
}

namespace C
{
    int A_b = 50;
    void func2()
    {
        cout <<"A_b:" <<A_b << endl;
    }
}

void func2()
{
    C::func2();
}

 

 

当写的命名空间为匿名的,相当于给其加上了static关键字

namespace
{
    int AB_b=10;
    int AB_a=20;
}

void func2()
{
    std::cout << "AB_b:" << AB_b <<std::endl;
    std::cout << "AB_a:" << AB_a <<std::endl;
}

 

 命名空间可以起别名

namespace C
{
    int A_b = 50;
    void func2()
    {
        cout <<"A_b:" <<A_b << endl;
    }
}
void func2()
{
    namespace MySpace = C;
    MySpace::func2();
}

 

 using

当using声明与就近原则同时出现,就会出错,类似于如下这种情况,这相当于声明了多次,编译器不知道用谁了

 

 

 using编译指令与就近原则同时出现,优先使用就近

namespace C
{
    int A_b = 50;
    int test = 50;
    void func2()
    {
        cout <<"A_b:" <<A_b << endl;
    }
}
void func2()
{
    int test = 20;
    using namespace C;
    cout << test << endl;
}

posted @ 2020-12-31 10:36  PYozo_free  阅读(226)  评论(0编辑  收藏  举报