1.在c++中, 名称可以是变量、函数、结构体、枚举、类以及类和结构体的成员。当项目越来越大时,名称相互冲突的可能性也将增加。使用多个厂商的类库时,可能导致名字冲突。例如,两个库可能都定义了名为List,Tree和Node的类,但定义的方式不兼容。用户可能希望使用一个库的List类,而使用另一个类库的Tree类。这种冲突被称为名字空间问题。
2.一个名字空间中的名称不会与另外一个名字空间中的相同名称冲突,同时允许程序的其他部分使用该名字空间中声明的东西。
3.名字空间可以使全局的,也可以嵌套在其他的名字空间中,但是不能位于代码块中。
4.名字空间是开放的,即可以把名称加入到名字空间中去。
namespace Jill { char * goose(const char *); }这样就将goose加入到了名字空间Jill中。
5.尽量使用using声明,少使用using编译,即多使用名字空间中的部分名称,尽量不要将名字空间中的全部名称导入到程序中。
6.
#include <iostream> using namespace std; int main() { ... }这个意思是,先将头文件iostream放到名字空间std中,然后,using编译指令是使该名字空间在文件下的函数中可用。
7.给名字空间取别名:
假设已有一个名字空间 namespace my_very_favorite_things {...}
则给这个名字空间取个别名mvft的方法: namespace mvft = my_very_favorite_things;
8.类似于math.h的头文件时与c语言兼容的,没有使用名字空间,但c++头文件cmath是将各种数学库函数放到名字空间std中。
9.名字空间实例:
以下程序由三个文件构成,一个头文件,两个源代码文件:
文件结构:
namesp.h代码:
#ifndef NAMESP_H_INCLUDED #define NAMESP_H_INCLUDED #include <string> namespace pers { struct Person { std::string fname; std::string lname; }; void getPerson(Person &); void showPerson(const Person &); } namespace debts { using namespace pers; struct Debt { Person name; double amount; }; void getDebt(Debt &); void showDebt(const Debt &); double sumDebt(const Debt ar[], int n); } #endif // NAMESP_H_INCLUDEDnamesp.cpp代码:
#include <iostream> #include "namesp.h" namespace pers { using std::cout; using std::cin; void getPerson(Person & per) { cout << "Enter first name: "; cin >> per.fname; cout << "Enter last name: "; cin >> per.lname; } void showPerson(const Person & per) { std::cout << per.lname << ", " << per.fname; } } namespace debts { using std::cout; using std::cin; using std::endl; void getDebt(Debt & debt) { getPerson(debt.name); cout << "Enter debt: "; cin >> debt.amount; } void showDebt(const Debt & debt) { showPerson(debt.name); cout << ": $" << debt.amount << endl; } double sumDebt(const Debt ar[], int n) { double total = 0; for(int i = 0; i < n; i++) total += ar[i].amount; return total; } }namespp.cpp代码:
#include <iostream> #include "namesp.h" using std::cin; using std::cout; using std::endl; void other(); int main() { using debts::Debt; using debts::showDebt; Debt debt = {{"zhang ", "fei"}, 2222.0}; showDebt(debt); other(); return 0; } void other() { using std::cout; using std::cin; using namespace debts; Person pr = {"Doodles", "Glister"}; showPerson(pr); cout << endl; Debt zippy[3]; for(int i = 0; i < 3; i++) getDebt(zippy[i]); for(int i = 0; i < 3; i++) showDebt(zippy[i]); cout << "Total debts is " << sumDebt(zippy, 3) << endl; }程序输出: