namespace解决名字冲突

 1 //header_one.h
2 #include <string>
3 #include <cmath>
4
5 using namespace std;
6
7 namespace ns_one
8 {
9 class Student
10 {
11 public:
12 Student(int n , string nam , int a)
13 {
14 num = n ;
15 name = nam ;
16 age = a ;
17 }
18 void get_data();
19 private:
20 int num ;
21 string name ;
22 int age ;
23 };
24
25 void Student::get_data()
26 {
27 cout << "num :" << num << "name :" << name << "age :" << age << endl ;
28 }
29
30 double fun(double a , double b)
31 {
32 return sqrt( a + b ) ;
33 }
34 }
35
36
37 //header_two.h
38 #include <iostream>
39 #include <cmath>
40
41 using namespace std;
42
43 namespace ns_two
44 {
45 class Student
46 {
47 public:
48 Student(int n , string nam , char se)
49 {
50 num = n ;
51 name = nam ;
52 sex = se ;
53 }
54 void get_data();
55 private:
56 int num ;
57 string name ;
58 char sex ;
59 };
60
61 void Student::get_data()
62 {
63 cout << "num :" << num << "name :" << name << "sex :" << sex << endl ;
64 }
65
66 double fun(double a , double b)
67 {
68 return sqrt( a - b );
69 }
70 }
71
72
73 //main file
74 #include <iostream>
75 #include "header_one.h"
76 #include "header_two.h"
77
78 using namespace std;
79
80 int main(void)
81 {
82 ns_one::Student stud1(101 , "Wang" , 18);
83 stud1::get_data();
84 cout << ns_one::fun(5 ,3) << endl ;
85 na_two::Student stud2(102 , "Li" , 'f');
86 stud2::get_data();
87 cout << ns_two::fun(5 ,3) << endl ;
88 return 0 ;
89 }

程序很简单,但有一点需要注意:

对象 stud1 是用 ns_one::Student 定义的,但对象 stud1 并不在命名空间 ns_one 中 。

stud1 的作用域为 main 函数范围内 。

在调用对象 stud1 的成员函数 get_data 时 , 应写成 stud1.get_data() , 而不应写成 ns_one::stud1.get_data() 。

posted @ 2011-10-24 15:34  MATRIX | yan  阅读(888)  评论(0编辑  收藏  举报