不包含string头文件,为何能运行成功

[root workspace]#cat hello.cpp

#include <iostream>
using namespace std;

int main()
{
    string first_name;
    cin >> first_name;
    if(first_name.size() > 2)
    cout<<"Hello world."<<endl;

    return 0;
}

[root workspace]#g++ hello.cpp
[root workspace]#g++ -Wall hello.cpp
[root workspace]#
[root workspace]#
[root workspace]#
[root workspace]#g++ -Wall -o hello hello.cpp
[root workspace]#
[root workspace]#
[root workspace]#./hello
12345
Hello world.
[root workspace]#

上面的代码,书上都有包含string头文件,我没包含,却运行成功了,这是为啥?
g++版本:
[root workspace]#g++ -v
使用内建 specs。
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
目标:x86_64-redhat-linux
配置为:../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bu... --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
线程模型:posix
gcc 版本 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)

阅读 3.1k
1 个回答

这个和编译器有关系,有的编译器在<iostream>中实现了<string>的声明,有的在<iostream>的前置头文件中包含了<string>的声明。但是为了更好的可移植性,最好还是添加<string>头文件。可以参考一下stackoverflow的回答

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题