头文件之惑 C++系列(2)(2006-11-21 10:16:17)

来源:互联网 发布:mac 优酷升级后 播放 编辑:程序博客网 时间:2024/06/05 08:22
===============
C++学习指导系列文章(2)
===============
***为了帮助大家学习C++,所以着手撰写系列文章,希望对大家有所帮助。有不当之处,也希望大家提建议。
***Bigleo 2006.11

头文件之惑

安装好VC6后,在inlude目录中,会看下列文件:
iostream
iostream.h
string
string.h
...
这些头文件,大多是成对出现。使用这些文件时,有的C++书(如钱能的C++程设计教程)中用有.h的头文件,有的C++书(如Nell dale的Programming in C++)中用没有.h的头文件。这是为什么?有.h的头文件与没有.h有头文件有什么区别?
有.h的头文件是为了与C更好的兼容,这是C++的目标之一:尽可能的包容C。其中的string、cin、cout等是以全局变量的方式定义的。C++1998-9-1标准如是讲:The ".h" headers dump all their names into the global namespace, whereas the newer forms keep their names in namespace std. Therefore, the newer forms are the preferred forms for all uses except for C++ programs which are intended to be strictly compatible with C.
无.h的头文件采用了名称空间技术,把cin、cout、string等放到了标准名字空间std中。在使用此类头文件时,如果要使用其中的内容,要指定标准名字空间。微软的文档中如是讲:
The ANSI/ISO C++ standard requires you to explicitly(显示地) declare the namespace in the standard library. For example, when using iostream, you must specify the namespace of cout in one of the following ways:
std::cout (explicitly)
using std::cout (using declaration)
using namespace std (using directive)
看一下下面这个例子所有的,会有什么错误:
#include
#include
#include
int main(){
    string st;
    st = "";
}
对,代码没有通过编译。因为在上面的代码中名字空间std 的成员不能被不加限定修饰地访问。为了修正这个错误我们可以选择下列方案之一:
用适当的限定修饰名代替例子中的名字空间std 成员的名字
用using 声明使例子中用到的名字空间std 的成员可见
用using 指示符使来自名字空间std 的全部成员可见
如改为如下代码,即可正确编译:
#include
#include
#include
using namespace std;
int main(){
    string st;
    st = "";
}

关于标准名称空间std,有些较早的C++书中称其会自动包含到程序中去,有些开发工具也是这样做的,比如说C++编译器gccgcc 2.9.x会自动加using namespace std。在 C++ ISO 1998-9-1标准要求显示的使用std,如GCC3.0.12,VC6,C++ Builder6都是这样。
原创粉丝点击