Skip to the content.

061-命名空间

命名空间可以解决相同方法签名的函数需要同时存在的问题

因为在c语言中没有命名空间,所以自己的库会给各个方法加上属于自己的前缀

类也是一种命名空间,所以经常看到ClassName::something

需要引用命名空间内的一些东西,使用::

:: 称为范围解析运算符

使用using namespace后,作用域内可以不用写namespace::something

可以特定导入命名空间内的一个方法using namespaceName::something,像下面这样

#include <iostream>

namespace Test1 {
    void print(const std::string &message) {
        std::cout << message << std::endl;
    }

    void printA(const std::string &message) {
        std::cout << "printA" << std::endl;
    }
}

int main() {
    using Test1::print;
    print("Message");
    //使用printA仍然要单独导入
    Test1::printA("message");
    return 0;
}

命名空间是可以嵌套的,像下面这样

#include <iostream>

namespace Test1 {
    namespace Test2 {
        void print(const std::string &message) {
            std::cout << message << std::endl;
        }
    }
}

int main() {
    Test1::Test2::print("message");
    return 0;
}

使用嵌套的namespace时 using namespace可以连续,也可以分开

#include <iostream>

namespace Test1 {
    namespace Test2 {
        void print(const std::string &message) {
            std::cout << message << std::endl;
        }
    }
}

int main() {
    using namespace Test1;
    using namespace Test2;
    print("message");
    return 0;
}
#include <iostream>

namespace Test1 {
    namespace Test2 {
        void print(const std::string &message) {
            std::cout << message << std::endl;
        }
    }
}

int main() {
    using namespace Test1::Test2;
    print("message");
    return 0;
}

可以为namespace定义别名,单个或者嵌套的均可

#include <iostream>

namespace Test1 {
    namespace Test2 {
        void print(const std::string &message) {
            std::cout << message << std::endl;
        }
    }
}

int main() {
    namespace a = Test1::Test2;;
    a::print("message");
    return 0;
}

尽量将using namespace限制在最小的范围内,如果将其写到文件开头,namespace就没有存在的意义了

namespace参考 https://zh.cppreference.com/w/cpp/language/namespace