命名空间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