using 指令和 include 预处理器指令是两个不同的东西。 include大致对应Java的CLASSPATH环境变量,或者java虚拟机的-cp选项。
它的作用是让编译器知道类型。例如,仅包括<string> 就可以让您参考std::string:
#include <string>
#include <iostream>
int main() {
std::cout << std::string("hello, i'm a string");
}
现在,使用指令就像 Java 中的 import。它们使名称在它们出现的范围内可见,因此您不必再完全限定它们。就像在 Java 中一样,必须知道使用的名称才能使其可见:
#include <string> // CLASSPATH, or -cp
#include <iostream>
// without import in java you would have to type java.lang.String .
// note it happens that java has a special rule to import java.lang.*
// automatically. but that doesn't happen for other packages
// (java.net for example). But for simplicity, i'm just using java.lang here.
using std::string; // import java.lang.String;
using namespace std; // import java.lang.*;
int main() {
cout << string("hello, i'm a string");
}
在头文件中使用 using 指令是一种不好的做法,因为这意味着碰巧包含它的每个其他源文件都会使用非限定名称查找来查看这些名称。与在 Java 中,您只使名称对出现导入行的包可见,而在 C++ 中,如果它们直接或间接包含该文件,它会影响整个程序。
在全局范围内执行此操作时要小心,即使在实现文件中也是如此。最好尽可能在本地使用它们。对于命名空间 std,我从不使用它。我和许多其他人总是在名字前面写上std::。但如果你碰巧这样做,就这样做吧:
#include <string>
#include <iostream>
int main() {
using namespace std;
cout << string("hello, i'm a string");
}
关于什么是命名空间以及为什么需要它们,请阅读 Bjarne Stroustrup 在 1993 年提出的将它们添加到即将到来的 C++ 标准中的提案。写的很好:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0262.pdf