目录
创建自己的命名空间是 C++ 中组织代码的一种好方法,特别是在开发大型项目或库时。命名空间可以帮助你避免名称冲突,并且清晰地组织代码。
std 是 C++ 标准库的命名空间。它是一个定义在 C++ 标准库中的所有类、函数和变量的命名空间。我们新建一个QTCreator的C++工程,默认生成的代码。(新建工程步骤在QT相关介绍中)
- #include
- using namespace std;
- int main()
- {
- cout << "Hello World!" << endl;
- return 0;
- }
在 C++ 中,如果你想使用标准库中的任何类、函数或对象,你通常有两种选择:
std::cout << "Hello, world!" << std::endl; - using namespace std;
- cout << "Hello, world!" << endl;
std 命名空间包含了许多类、函数和对象,例如:输入输出库(如 std::cout , std::cin , std::endl )
std 命名空间是 C++ 编程的基础部分,理解和正确使用它对于编写健壮和高效的 C++ 代码至关重要。
假设我们要创建一个命名空间来包含与圆形相关的功能。我们可以命名这个命名空间为 Cir :
创建 Cir 自定义命名空间头文件


初始化界面如下

编写代码如下
cir.h
- #ifndef CIR_H
- #define CIR_H
-
- namespace cir {
- double PI = 3.141592653;
- //获取圆形周长的函数
- double getlengthOfCircle(double radius)
- {
- return 2*PI*radius;
- }
- //获取圆形面积的函数
- double getAreaOfCircle(double radius)
- {
- return PI*radius*radius;
- }
- }
-
- #endif // CIR_H
main.cpp(使用cir前缀)
在 main.cpp 中,我们首先包含了定义 Cir 命名空间的头文件。然后,我们可以使用 Cir:: 前缀来访问该命名空间中的函数和常量。
- #include
- #include "cir.h"//包含前面所定义的命名空间头文件
- #include
-
- using namespace std;
-
- int main()
- {
- double MyRadius = 5;
- cout << "Hello World!" << endl;
- printf("Length%f, Area:%f\n",cir::getlengthOfCircle(MyRadius),cir::getAreaOfCircle(MyRadius));
- return 0;
- }
main.cpp(使用 using namespace cir ;)
通过使用自定义命名空间,你可以有效地组织你的代码,并减少不同库之间的名称冲突。这在大型项目和团队协作中尤其重要。
- #include
- #include "cir.h"
- #include
-
- using namespace std;
- using namespace cir;
-
- int main()
- {
- double MyRadius = 5;
- cout << "Hello World!" << endl;
- printf("Length%f, Area:%f\n",getlengthOfCircle(MyRadius),getAreaOfCircle(MyRadius));
- return 0;
- }