using 指令和 include 预处理器指令是两个不同的东西。include
大致对应Java的环境CLASSPATH
变量,或者-cp
java虚拟机的选项。
它所做的就是让编译器知道这些类型。仅包括<string>
例如将使您能够参考std::string
:
#include <string>
#include <iostream>
int main() {
std::cout << std::string("hello, i'm a string");
}
现在,使用指令就像import
在 Java 中一样。它们使名称在它们出现的范围内可见,因此您不必再完全限定它们。就像在 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