命名空間namespace
最常見的命名空間是std,你一定非常熟悉,也就是:
using namespace std;
命名空間的基本格式
注意,要在頭文件里面定義!
namespace namespace_name{data_type function_name(data_type parameter){data_type result;//function contentreturn result;}
}
自定義的命名空間
我們可以在頭文件里面自定義一個命名空間,步驟為:
- 創建一個新的頭文件,比如"square.h"
- 在main.c中引用該頭文件:
#include "square.h"//自己定義的.h頭文件需要用雙引號
- 在"square.h"頭文件中進行編碼
#ifndef SQUARE_H
#define SQUARE_Hnamespace square{int area(int wid,int len){return wid*len;}int around(int wid,int len){return wid*2+len*2;}
}#endif // SQUARE_H
- 在main函數中調用該命名空間,具體有兩種調用方式
方式一 每次調用都指明命名空間:
#include <iostream>
#include "square.h"using namespace std;int main()
{int wid=10;int len=5;cout << square::area(wid,len) << endl;return 0;
}
方式二 在main函數前聲明使用的命名空間,適用于小型項目
#include <iostream>
#include "square.h"using