003_linuxC++之_namespace使用
(一)引入namespace原因:
假如有很多跟人共同完成一项工程,工程中难免会有函数定义一样的名称,不可能一个一个的询问这个函数 你定义过了没有,所以引入namespace
1 #include <stdio.h> 2 #include "person.h" 3 #include "dog.h" 4 5 /*global namespace*/ 6 /*把A::person放入global namespace,以后可以使用person来表示A::person*/ 7 using namespace A; 8 using namespace C; 9 10 11 int main(int argc,char ** argv) 12 { 13 /*local namespace*/ 14 Person per; 15 Dog dog; 16 per.setName("zhangsan"); 17 per.setAge(10); 18 per.printInfo(); 19 20 dog.setName("lisi"); 21 dog.setAge(20); 22 dog.printInfo(); 23 24 A::printVersion(); 25 C::printVersion(); 26 return 0; 27 }
1 #include <stdio.h> 2 namespace A{ 3 4 class Person{ 5 private: 6 char *name; 7 int age; 8 char *work; 9 10 public: 11 void setName(char *name); 12 int setAge(int Age); 13 void printInfo(void); 14 }; 15 16 void printVersion(void); 17 }
1 #include <iostream> 2 #include "person.h" 3 using namespace std; 4 5 namespace A{ 6 void Person::setName(char *name) 7 { 8 this->name = name; 9 } 10 int Person::setAge(int Age) 11 { 12 if(Age < 0 || Age > 150) 13 { 14 this->age = 0; 15 return -1; 16 } 17 this->age = Age; 18 return 0; 19 } 20 void Person::printInfo(void) 21 { 22 cout<<"nane = "<<name<<"age = "<<age<<"work = "<<work<<endl; 23 //intf("name = %s, age = %d, work = %s\n",name,age,work); 24 } 25 26 void printVersion(void) 27 { 28 cout<<"Person V1, by luxiaoguo"<<endl; 29 //intf("Person V1, by luxiaoguo\n"); 30 } 31 32 33 }
1 namespace C{ 2 3 class Dog{ 4 private: 5 char *name; 6 int age; 7 char *work; 8 9 public: 10 void setName(char *name); 11 int setAge(int age); 12 void printInfo(void); 13 }; 14 15 void printVersion(void); 16 17 }
1 #include <stdio.h> 2 #include "dog.h" 3 4 namespace C{ 5 6 void Dog::setName(char *name) 7 { 8 this->name = name; 9 } 10 int Dog::setAge(int Age) 11 { 12 if(Age < 0 || Age > 150) 13 { 14 this->age = 0; 15 return -1; 16 } 17 this->age = Age; 18 return 0; 19 } 20 void Dog::printInfo(void) 21 { 22 printf("name = %s, age = %d, work = %s\n",name,age,work); 23 } 24 25 void printVersion(void) 26 { 27 printf("Dog V1, by luxiaoguo\n"); 28 } 29 }