zoukankan      html  css  js  c++  java
  • 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 

  • 相关阅读:
    wepack使用
    js 原型链
    react 生命周期
    settimeout--原来定时器是有三个及以上参数的
    我所未知的 typeof 现象
    js 里面的 function 与 Function
    ECMAScript 对象类型
    js阻碍DOM加载
    面试问题与心得
    Java IO 乱码
  • 原文地址:https://www.cnblogs.com/limera/p/namespace.html
Copyright © 2011-2022 走看看