现在的位置: 首页 > 综合 > 正文

c++ namespace 命名空间

2013年12月01日 ⁄ 综合 ⁄ 共 589字 ⁄ 字号 评论关闭

       // name.h
            namespace A
            {
                 int fun();
            }

            namespace B
            {
                 int fun();
            }

          // name.cpp
            #include "name.h"

            int A::fun()
            {
                 return 1;
            }

            int B::fun()
            {
                 return 2;
            }

          // main.cpp
            #include <iostream>
            #include "name.h"

            using namespace std;
            using namespace B;

            void main(void)
            {
                 cout << "result = " << fun() << endl;
            }

// 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(); 
}

抱歉!评论已关闭.