转自:http://www.cnblogs.com/autocrat/archive/2010/05/05/1727630.html

namespace是为了解决C++中的名字冲突而引入的。
什么是名字冲突呢?比如,在文件x.h中有个类MyClass,
在文件y.h中也有个类MyClass,而在文件z.cpp中要同时
引用x.h和y.h文件。显然,按通常的方法是行不能的,
那怎么办呢?引入namespace即可。例如:
      在x.h中的内容为
// x.h
namespace MyNamespace1
{
   class MyClass
   {
   public:
      void f();
   private:
      int m;
   }
};

      在y.h中的内容为
// y.h
namespace MyNamespace2
{
   class MyClass
   {
   public:
      void f();
   private:
      int m;
   }
};

   然后在z.cpp中引入x.h和y.h
// z.cpp
#include"x.h"   
#include"y.h"   

void z::f()
{
   //声明一个文件x.h中类MyClass的实例x
   MyNamespace1::MyClass x;
    //声明一个文件x.h中类MyClass的实例x
   MyNamespace2::MyClass y;

 

  //调用文件x.h中的函数f
   x.f();
   //调用文件y.h中的函数f
   y.f();
}
      名字空间实质上是一个作用域。

相关文章:

  • 2021-09-05
  • 2021-11-02
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-29
  • 2021-11-04
  • 2021-09-29
  • 2022-02-26
  • 2021-09-05
  • 2021-07-17
  • 2021-11-14
相关资源
相似解决方案