Chinaunix

标题: C++ string 为什么会这样 [打印本页]

作者: zjw0722    时间: 2014-07-16 15:29
标题: C++ string 为什么会这样
代码1:
  1. #include <iostream>

  2. using namespace std;

  3. int main(int argc, char** argv)
  4. {
  5.         string s("Hello World!");
  6.         cout << s << endl;

  7.         return 0;
  8. }
复制代码
代码2:
  1. #include <iostream>

  2. int main(int argc, char** argv)
  3. {
  4.         string s("Hello World!");
  5.         std::cout << s << std::endl;

  6.         return 0;
  7. }
复制代码
代码1运行正常

代码2编译出错,提示string没有定义。

这也是小菜我前几天面试被问到的问题,自己想了很久没有想明白,为什么string使用的时候不需要导入头文件#include <string>,而只需要声明了标准命名空间就可以使用了。
那么#include <string>在什么时候才必须导入呢?

谢谢!


作者: bruceteen    时间: 2014-07-16 16:03
第一个问题:
第二段代码 string 前加 std::

第二个问题:
因为 operator<<( ostream&, const std::string& ) 声明在<iostream>中,所以<iostream>中必然得包含std::string的定义。
但用到 std::string 就应该 #include <string>,不要把精力浪费在无聊的事上。
作者: wangspace    时间: 2014-07-16 16:44
学习了:wink:
作者: zjw0722    时间: 2014-07-16 19:06
bruceteen 发表于 2014-07-16 16:03
第一个问题:
第二段代码 string 前加 std::


额,知道了,刚看了一下开源中国上iostream的头文件,没有直接包含string头文件,不知道是不是间接包含了。


谁知道面试的时候会被问到这么奇葩的问题啊,彻底没谱儿。
作者: myworkstation    时间: 2014-07-17 15:22
回复 1# zjw0722


    在面试的时间问这么蛋疼的问题,纯粹是吹毛求疵的态度,这样的公司不值一去。这个问题完全依赖于stl库的实现,能编译通过是因为隐式的依赖。以gnu的stl实现为例,其头文件包含关系如下:
iostream包含了头文件istream,ostream,而这两个头文件都包含了ios,而ios包含了bits/ios_base.h,ios_base.h中包含了bits/locale_classes.h,最终locale_classes.h中包含了string头文件。

iostream=>(istream,ostream)=>ios=>bits/ios_base.h=>bits/locale_classes.h=>string

第二个编译不过是因为不加std前缀的话找不到相应的类型。实现上文件已经被隐式包含了。
作者: myworkstation    时间: 2014-07-17 15:24
回复 2# bruceteen


    就实现来看这个操作符重符都是在basic_string中,不会在stream中直接实现。楼主的问题实际上是隐含包含了头文件造成的。
作者: zjw0722    时间: 2014-07-19 20:14
回复 5# myworkstation

嗯,我这刚毕业,面试就遇到这问题,嗯,最后也没去那公司。


   
作者: zjw0722    时间: 2014-07-19 20:15
回复 6# myworkstation
嗯,知道了,谢谢,终于搞明白了


   




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2