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 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM