为什么 random() 在 cstdlib 中起作用? (乌班图10.10)
我一直以为cstdlib中的随机函数只有rand和srand,但是以下有效(在Ubuntu 10.10上用g++编译)?
事实上,当我从 Windows 迁移到 Ubuntu 时,我发现了这一点,我的编译失败了,因为它模糊地重载了(我已经声明了我自己的“random()”函数)。
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
srandom(50);
cout << random();
return 0;
};
另外,以下内容在 Ubuntu 上可以正确编译,在检查 stdlib.h 后,发现 random() 和 srandom() 等并未在 std 命名空间中声明。这使得它完全是屁股上的痛苦......
#include <iostream>
#include <cstdlib>
int main() {
std::cout << random();
return 0;
};
I always thought the random functions in cstdlib were only rand and srand, but the following works (compiled with g++ on Ubuntu 10.10)?
I actually found this out when moving from Windows to Ubuntu, my compilation failed as it was ambiguously overloading (I had declared my own 'random()' function).
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
srandom(50);
cout << random();
return 0;
};
Also the following compiles correctly on Ubuntu, it appears after checking stdlib.h, that the random() and srandom(), among others, are not declared in the std namespace. Which makes it a complete pain in the arse...
#include <iostream>
#include <cstdlib>
int main() {
std::cout << random();
return 0;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
random()
是 单一 Unix 规范。它不是 C++ 标准的一部分。这就是为什么它不在 Windows 上,但在大多数 Unix/Mac 平台上都可以找到。random()
is part of the Single Unix Specification. It’s not part of the C++ Standard. That’s why it’s not on Windows but is found on most Unix/Mac platforms.因为编译器编写者可以自由地向语言库添加额外的东西,以使您的工作更轻松。通常,这不会成为问题,因为它将它们放在一个您不会添加内容的命名空间中,
std
。你的问题是由那条小线引起的
这会将
std
中的所有内容拉入程序的命名空间,包括编译器编写者帮助提供的std::random
。如果您显式声明从std
中提取的内容,则不会使用std::random
破坏本地random
:另请参阅这个问题来自 c++ FAQ lite。
Because compiler writers are free to add extra things to the language library to make your job easier. Normally, it wouldn't be a problem, because it puts them in a namespace which you won't be adding things to,
std
.Your problem arises from that little line
This pulls everything from
std
into your program's namespace, includingstd::random
, which the compiler writers helpfully provided. If you instead explicitly declare what you're pulling fromstd
, you wouldn't clobber your localrandom
withstd::random
:See also this question from the c++ FAQ lite.