關於C++自定義命名空間,今天驗證了一下命名空間如何使用,和嵌套命名空間以及出現的bug。
- 如何自定義命名空間,實例如下:
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

#include<iostream> #include"insertion_sort.h" void insert::insertion_sort::call() { std::cout<<"你調用的是插入算法"<<std::endl; //命名空間的使用和類相似 }
recursive.h和recursive.cpp

#pragma once #ifndef _RECURSIVE_ #define _RECURSIVE_ namespace recur{ class recursive { public: static void call(); }; } #endif

#include<iostream> #include"recursive.h" void recur::recursive::call() { std::cout<<"你調用的是遞歸算法"<<std::endl; }
二者在主函數中的調用:
#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