cpp: namespace -- (不同头文件的命名空间,具有相同名称)

发布时间 2024-01-06 06:11:43作者: lnlidawei

cpp:   namespace -- (不同头文件的命名空间,具有相同名称)

 

 

 

 

一、说明:

 

  1、探索:在多个头文件中,定义相同名称的命名空间。

 

 

 

 

二、代码

 1 // first.cpp
 2 #include <iostream>
 3 #include <string>
 4 #include "first.h"
 5 
 6 using namespace std;
 7 
 8 void lidawei::msg()
 9 {
10         cout << "lidawei::msg() ..." << endl;
11 }
12 
13 
14 // first.h
15 namespace lidawei
16 {
17         void msg();
18 }
19 
20 
21 // second.cpp
22 #include <iostream>
23 #include <string>
24 #include "second.h"
25 
26 using namespace std;
27 
28 void lidawei::say()
29 {
30         cout << "lidawei::say() ..." << endl;
31 }
32 
33 
34 // second.h
35 namespace lidawei
36 {
37         void say();
38 }
39 
40 
41 // test.cpp
42 #include "first.h"
43 #include "second.h"
44 
45 int main()
46 {
47         lidawei::msg();
48         lidawei::say();
49 
50         return 0;
51 }

 

 

 

三、运行

1 [wit@fedora namespace]$ alias | grep "gpp"
2 alias gpp='g++ -g -Wall -std=c++20 -o'
3 [wit@fedora namespace]$ 
4 [wit@fedora namespace]$ 
5 [wit@fedora namespace]$ gpp nstest test.cpp first.cpp second.cpp && ./nstest
6 lidawei::msg() ...
7 lidawei::say() ...
8 [wit@fedora namespace]$ 
9 [wit@fedora namespace]$ 

 

 

 

四、参考文档:

 

  1、c++ 命名空间|菜鸟教程  https://www.runoob.com/cplusplus/cpp-namespaces.html