C++自定义命名空间

关于C++自定义命名空间,今天验证了一下命名空间如何使用,和嵌套命名空间以及出现的bug。

  1. 如何自定义命名空间,实例如下:

   insertion_sort.h和insertion_sort.cpp

#pragma once
#ifndef _INSERTION_SORT_
#define _INSERTION_SORT_

namespace insert{
    class insertion_sort
    {
    public:
        static void call();  //定义为类的静态函数,只是为了demo的时候方便调用
    };

    }

#endif
View Code
#include<iostream>
#include"insertion_sort.h"

void insert::insertion_sort::call()
{
    std::cout<<"你调用的是插入算法"<<std::endl;   //命名空间的使用和类相似

}
View Code

recursive.h和recursive.cpp

#pragma once
#ifndef _RECURSIVE_
#define _RECURSIVE_

namespace recur{
    class recursive
    {
    public:
        static void call();
    };
}

#endif
View Code
#include<iostream>
#include"recursive.h"

void recur::recursive::call()
{
    std::cout<<"你调用的是递归算法"<<std::endl;

}
View Code

二者在主函数中的调用:

#include<iostream>
#include "insertion_sort.h"
#include"recursive.h"

int main()
{
    
    recur::recursive::call();
    insert::insertion_sort::call();
        
}

 

   2.嵌套命名空间

#pragma once
#ifndef _INSERTION_SORT_
#define _INSERTION_SORT_

namespace insert{
    class insertion_sort
    {
    public:
        static void call();
    };

    namespace hello{
        void out()
        {
            std::cout<<"你现在调用的是hello函数"<<std::endl;
        }
    }
}

#endif
//main.cpp
#include<iostream>
#include "insertion_sort.h"


int main()
{
    
    recur::recursive::call();
    insert::hello::out();
    
}


当这样直接在VS2010上运行的时候,会出现bug:LNK1169: 找到一个或多个多重定义的符号,解决方法参考:http://blog.chinaunix.net/uid-25498312-id-4254097.html,我采用的是:.在项目->属性->链接器->命令行->附加选项中加   /force 

 

posted @ 2015-11-03 20:20  学会走路  阅读(5155)  评论(0编辑  收藏  举报