namespace

解决名字冲突问题
假设这样一种情况,当一个班上有两个名叫 Zara 的学生时,为了明确区分它们,我们在使用名字之外,不得不使用一些额外的信息,比如他们的家庭住址,或者他们父母的名字等等。
同样的情况也出现在 C++ 应用程序中。例如,您可能会写一个名为 xyz() 的函数,在另一个可用的库中也存在一个相同的函数 xyz()。这样,编译器就无法判断您所使用的是哪一个 xyz() 函数。
因此,引入了命名空间这个概念,专门用于解决上面的问题,它可作为附加信息来区分不同库中相同名称的函数、类、变量等。使用了命名空间即定义了上下文。本质上,命名空间就是定义了一个范围。
我们举一个计算机系统中的例子,一个文件夹(目录)中可以包含多个文件夹,每个文件夹中不能有相同的文件名,但不同文件夹中的文件可以重名。

命名空间 - 图1
image.png
image.png

  1. #include <stdlib.h>
  2. #include <Windows.h>
  3. #include <stdio.h>
  4. namespace ns1 {
  5. int x;
  6. void Fn() {
  7. printf("ns1::Fn\n");
  8. }
  9. class CObject
  10. {
  11. public:
  12. void Test() {
  13. printf("sn1::CObject::Test\n");
  14. }
  15. };
  16. }
  17. namespace ns2 {
  18. int x;
  19. void Fn() {
  20. printf("ns2::Fn\n");
  21. }
  22. class CObject
  23. {
  24. public:
  25. void Test() {
  26. printf("sn2::CObject::Test\n");
  27. }
  28. };
  29. }
  30. int main() {
  31. printf("%d \n", ns1::x);
  32. printf("%d \n", ns2::x);
  33. ns1::Fn();
  34. ns2::Fn();
  35. ns1::CObject c;
  36. return 0;
  37. }

太麻烦了

使用using

#include <stdlib.h>
#include <Windows.h>
#include <stdio.h>

namespace ns1 {
    int x;
    void Fn() {
        printf("ns1::Fn\n");
    }
    class CObject
    {
    public:
        void Test() {
            printf("sn1::CObject::Test\n");
        }
    };

}
namespace ns2 {
    int x;
    void Fn() {
        printf("ns2::Fn\n");
    }
    class CObject
    {
    public:
        void Test() {
            printf("sn2::CObject::Test\n");
        }
    };

}

using namespace ns1;

int main() {
    printf("%d \n", x);
    printf("%d \n", ns2::x);
    Fn();
    ns2::Fn();
    CObject c;

    return 0;
}

全局命名空间

::test();
:: //全局命名空间

还是冲突?
加上前缀