using声明和using编译指令
- using声明由被限定的名称和其前面的关键字using组成的,它将特定的名称添加到它所属的声明区域中。如果在函数内部使用using声明,会把这个特定加入到函数这个内部区域中,如果在函数外面,则就是将这个名称添加到全局名称空间中。
- using编译指令由名称空间名和前面关键字using namespace组成,它使得空间中的所有名称都可以使用,而且并不需要域操作符。和声明一样,如果将using编译指令加入到全局声明区域中,该名称空间中的所有名称全局可用,在函数中声明,则就在函数的这个区域。
实现:
- 这是头文件的代码:(namesp.h)
namespace pers{
const int Len = 50;
struct Person{
char fname[Len];
char lname[Len];
};
void getPerson(Person &);
void showPerson(const Person&);
}
namespace debts{
using namespace pers;
struct Debt{
Person name;
double count;
};
void getDebt(Debt&);
void showDebt(const Debt&);
double sumDebts(const Debt ar[],int n);
}
- 这是实现头文件中具体函数的代码:(namesp.cpp)
#include<iostream>
#include "namesp.h"
namespace pers{
using std::cout;
using std::cin;
void getPerson(Person& rp){
cout<<"Enter first name:";
cin>>rp.fname;
cout<<"Enter last name:";
cin>>rp.lname;
}
void showPerson(const Person& rp){
std::cout<<rp.lname<<"."<<rp.fname;
}
}
namespace debts{
void getDebt(Debt& rd){
getPerson(rd.name);
std::cout<<"Enter Debt:";
std::cin>>rd.count;
}
void showDebt(const Debt& rd){
showPerson(rd.name);
std::cout<<": $"<<rd.count<<std::endl;
}
double sumDebts(const Debt ar[],int n){
double total = 0;
for (int i = 0 ; i < n ; i++){
total += ar[i].count;
}
return total;
}
}
- 这是调用命名空间案例的代码:(namessp.cpp)
#include<iostream>
#include "namesp.cpp"
void other();
void another();
int main(){
using debts::Debt;
using debts::showDebt;
Debt golf = {{"Benny","Gotasniff"},120.0};
showDebt(golf);
other();
another();
}
void other(){
using std::cin;
using std::cout;
using std::endl;
using namespace debts;
Person dg = {"Doodles","Glister"};
showPerson(dg);
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 debt:$"<<sumDebts(zippy,3)<<endl;
return;
}
void another(){
using pers::Person;
Person collector = {"Milo","Rightshift"};
pers::showPerson(collector);
std::cout<<std::endl;
}
这是测试数据,自行copy,运行呢。
/*
Arabella
Binx
100
Cleve
Delaproux
120
Eddie
Fiotox
200
*/
运行结果如下:
Gotasniff.Benny: $120
Glister.Doodles
Enter first name:Arabella
Enter last name:Binx
Enter Debt:100
Enter first name:Cleve
Enter last name:Delaproux
Enter Debt:120
Enter first name:Eddie
Enter last name:Fiotox
Enter Debt:200
Binx.Arabella: $100
Delaproux.Cleve: $120
Fiotox.Eddie: $200
Total debt:$420
Rightshift.Milo
命名空间指导原则
- 使用已命名的名称空间中声明的变量,而不是使用外部全局变量。
- 使用已命名的名称空间中声明的变量,而不是使用静态全局变量。
- 如果开发了一个函数库或者类库,将其放入一个命名空间中。
- 仅将编译指令using作为一种将旧代码转换使用名称空间的权宜之计。
- 不要在头文件中使用using编译指令。首先,这样掩盖了要让那些名称可用,另外,包含头文件的使用顺序可能影响程序的行为,如果非要加入using编译指令,应该将其加入到预处理编译指令#include之后。
- 导入名称时,首先使用域解析操作符或者using声明方法。
- 对于using声明,首先将其作用域设置为局部。