本文介绍了为什么rand()以及为什么在cstdlib的global和std名称空间中都存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道rand()作为<cstdlib>的示例功能,在全局和std命名空间中都存在.

I understand that rand(), as an example function from <cstdlib>, exists both in the global and the std namespace.

实际上,以下内容将正确编译,即,对std::rand()rand()的调用都是合法的.

In effect the following will compile without errors, i.e. both calls to std::rand() and rand() will be legit.

#include <cstdlib>    
int main() {
    std::rand();
    rand();    
}

它的用途是什么,它是如何实现的(函数在两个名称空间中)?

What is the use for this and how exactly is it implemented (the function being in both namespaces)?

推荐答案

行为是根据标准的 Uspecified行为.
按照包含cstdlib的标准,在std命名空间中以及可能在Global命名空间中导入符号名称.如果您依赖于包含在全局命名空间中的符号名称,则您的程序是不可移植的,并且您依赖于特定实现的行为.

The behavior is Uspecified behavior as per standard.
As per the standard including cstdlib imports the symbol names in std namespace and possibly in Global namespace. If you rely on symbol names being included in global namespace then your program is non portable and you are relying on behavior of a specific implementation.

要不依赖于实现行为,您必须:

To not rely on the implementatio behavior you must:

包括cstdlib并为rand使用完全限定名称.

Include cstdlib and use fully qualified name for rand.

std::rand()


参考文献:


References:

C ++ 11 Standard:D.5 C标准库标头
第3段:


好读物:
我应该包含< xxxx.h>或< cxxxx>在C ++程序中?


Good Read:
Should I include <xxxx.h> or <cxxxx> in C++ programs?

这篇关于为什么rand()以及为什么在cstdlib的global和std名称空间中都存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 12:04