可以用来避免命名冲突。

使用namespace 名字来定义一个命名空间。使用的时候,在全局变量函数前面加上空间名字::即可指定命名空间。

class Person
{
private:
    int age;

public:
    void set_age(int);

    int get_age();
};

namespace zhoupb
{
    int a;
    
    void fun() {  }
    
    class Person
    {
    private:
        int id;

    public:
        Person(/* args */);
        ~Person();
        void set_id(int id);
        int get_id();
    };
    
    Person::Person(/* args */) { }
    
    Person::~Person() { }
    
    void Person::set_id(int id)
    {
        this->id = id;
    }

    int Person::get_id()
    {
        return this->id;
    }
}

int main()
{
    Person p; // 使用默认的命名空间
    p.set_age(10);

    zhoupb::Person p1; // 使用zhoupb的命名空间
    p1.set_id(1);
    
    zhoupb::a = 10;
    zhoupb::fun();
    return 0;
}

使用命名空间

也可以在使用的时候,在函数里加上using namespace 空间名字。意味着,在这个作用域,不用写命名空间的前缀。

int test()
{
    using namespace zhoupb;

    a = 10;

    fun();

    Person p;
    p.set_id(1);
}

嵌套命名空间

命名空间也是可以嵌套的。

namespace A
{
    int a;
    namespace B
    {
        int b;
    }
}

int main()
{
    A::a = 10;
    A::B::b = 10;
    using namespace A::B;
    return 0;
}

默认命名空间

有个默认的全局命名空间,我们创建的命名空间默认都嵌套在它里面。它没有名字。

void fun()
{
    // ...
}

namespace A
{
    void fun()
    {
        // ...
    }
}

int main()
{
    // 使用A命名空间里的fun()
    A::fun();
    // 使用默认命名空间里的fun()
    ::fun();
    return 0;
}

合并命名空间

下面两种写法的等价的。

namespace a
{
    int a;
}

namespace a
{
    int b;
}
namespace a
{
    int a;
    int b;
}

通常类的声明和实现都是分开的,一般也有命名空间的。按照命名空间的合并所说的,在声明和实现外面都要写上命名空间的定义。

#paragma once
namespace zhoupb
{
    class Person
    {
        private:
            int age;
        public:
            void set_age(int);

            int get_age();

            Person();

            ~Person();
    };
}
// person.cpp
#include "person.h"

namespace zhoupb
{
    void Person::set_age(int age)
    {
        this->age = age;
    }

    int Person::get_age()
    {
        return this->age;
    }

    Person::Person()
    {
        // ...
    }

    Person::~Person()
    {
        // ...
    }   
}