为什么rand()在不包含cstdlib或不使用命名空间std的情况下进行编译? [英] Why does rand() compile without including cstdlib or using namespace std?

查看:103
本文介绍了为什么rand()在不包含cstdlib或不使用命名空间std的情况下进行编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我正在阅读的书, rand()在C ++中需要 #include< cstdlib>

但是,我能够编译使用 rand()的以下代码,而无需 #include< cstdlib> 使用命名空间std; 在Visual Studio 2015中。

为什么不需要编译这两个文件?我应该包含cstdlib吗?



C ++代码:

  #include< ; iostream> 

int main()
{
std :: cout<< rand()<< std :: endl;
}


解决方案

有两个问题:


  1. 标准库头文件可能包括其他标准库头文件。因此, iostream 可以直接或间接包含 cstdlib

  2. 带有C的头文件允许使用-standard库等效项(例如 cstdlib )将C标准库名称带入全局名称空间,即,在 std 命名空间(例如 rand 。)自C ++ 11起正式允许使用此名称空间,并且在很大程度上以前是允许的。 >

    According to the book I'm reading, rand() requires #include <cstdlib> in C++
    However, I am able to compile the following code that uses rand() without #include <cstdlib> nor using namespace std; in Visual Studio 2015.
    Why are these two not needed to compile? Should I include cstdlib?

    C++ Code:

    #include <iostream>
    
    int main()
    {
        std::cout << rand() << std::endl;
    }
    

    解决方案

    There are two issues at play:

    1. Standard library header files may include other standard library header files. So iostream may include cstdlib directly or indirectly.
    2. Header files with C-standard library equivalents (e.g. cstdlib) are allowed to bring C standard library names into the global namespace, that is, outside of the std namespace (e.g. rand.) This is formally allowed since C++11, and was largely tolerated before.

    这篇关于为什么rand()在不包含cstdlib或不使用命名空间std的情况下进行编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆