提到using就不得不提到 :: 作用域符。
作用域符表示访问的作用域,比如命名空间,类名,等等,默认为当前文件下,包括include的内容。
举个例子。
#include<stdio.h>
#include<iostream>
namespace mine{
void printf(char*out){
std::cout<<out<<std::endl;
}
};
using namespace mine;
int main(){
printf("hello\n");
return 0;
}
如果我们想要访问mine里面的就需要显示的调用
#include<stdio.h>
#include<iostream>
namespace mine{
void printf(char*out){
std::cout<<"mine"<<std::endl;
std::cout<<out<<std::endl;
}
};
using namespace mine;
int main(){
mine::printf("hello\n");
return 0;
}
有的时候会出现我们可以显示的调用namespace里面的,但是需要调用当前作用域的,那么我们就需要通过作用域符来进行显示的调用。即 ::printf
#include<stdio.h>
#include<iostream>
namespace mine{
void printf(char*out){
std::cout<<"mine"<<std::endl;
std::cout<<out<<std::endl;
}
};
using namespace mine;
int main(){
::printf("hello\n");
return 0;
}
我们使用using导致的结果就是在无需使用前缀的情况下也可以使用这个名字。我们可以使用整个命名空间的方法,即。
using namespace mine;
也可以使用某一个方法。
using std::cout;
cout<<"aaa"<<std::endl;
我们甚至可以在类里面给父类的成员变量提升权限。比如protected升级为public。
public:
using father::protected_member;
在没有头文件保护符的情况下,如果我们使用了using,就会多次的包含某个命名空间。这个就和程序员的编码习惯有关系了。
所以如何使用需要根据我们的具体情况而定。