Why does rand() compile without including cstdlib or using namespace std?(为什么 rand() 编译时不包含 cstdlib 或使用命名空间 std?)
问题描述
根据我正在阅读的书,rand() 在 C++ 中需要 #include
但是,我能够编译以下使用 rand() 的代码,而无需 #include <cstdlib> 或 using namespace std; 在 Visual 中工作室 2015.
为什么这两个不需要编译?我应该包括 cstdlib 吗?
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++ 代码:
#include <iostream>
int main()
{
std::cout << rand() << std::endl;
}
推荐答案
有两个问题在起作用:
- 标准库头文件可能包含其他标准库头文件.所以
iostream可以直接或间接包含cstdlib. - 具有 C 标准库等效项(例如
cstdlib)的头文件可以将 C 标准库名称带入全局命名空间,即在std命名空间之外(例如rand.)这是从 C++11 开始正式允许的,并且在之前被广泛容忍.
- Standard library header files may include other standard library header files. So
iostreammay includecstdlibdirectly or indirectly. - 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 thestdnamespace (e.g.rand.) This is formally allowed since C++11, and was largely tolerated before.
这篇关于为什么 rand() 编译时不包含 cstdlib 或使用命名空间 std?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 rand() 编译时不包含 cstdlib 或使用命名空间 std?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
