为什么iostream定义了一个abs函数,我该如何阻止它? [英] Why does iostream define an abs function, and how can I stop it?
问题描述
以下c ++代码不会编译:
int main(){
double a = abs(5.1 );
返回0;
}
它抱怨 abs
当然没有定义。但是下面的代码不会编译:
#include< iostream>
int main(){
std :: cout<< abs(5.1)<<的std :: ENDL;
std :: cout<< abs(-5.1)<<的std :: ENDL;
返回0;
}
输出两个5(不是5.1)。这很糟糕,原因很多。首先, abs
是这样一个自然而常用的函数,我一直都在使用它,但是 int
部分几乎是从来没有我想要返回。其次,对于我(或者使用我的代码的人)来说,写入 abs
并不会注意到它会编译,但做错了事,因为我(他们)真的很擅长忽略警告。第三,我只是明白不明白为什么iostream无论如何都会定义一个 abs
函数。第四,我真的不明白为什么它进入全局名称空间。
有没有什么办法可以防止这种令人反感的<$ c
重要的是,我使用
gcc version 4.2.1(基于Apple Inc. build 5658)(LLVM build 2335.6)
最有可能 iostream
包含 stdlib.h
做一些工作。这是头文件的C版本,它只在全局命名空间中为 int
声明 abs
对于 double
值,使用 fabs
)。
m没有意识到有任何具体的方法来保持 abs
不被包含在内,但我知道g ++ 4.5在没有多余的东西时更好 由基本包括如 iostream
和字符串
。
也许可以得到一个警告,即double被截断为int(EDIT:是,使用 -Wconversion
来警告)。
The following c++ code does not compile:
int main() {
double a = abs(5.1);
return 0;
}
It complains that abs
is not defined, of course. But the following does compile:
#include <iostream>
int main() {
std::cout << abs(5.1) << std::endl;
std::cout << abs(-5.1) << std::endl;
return 0;
}
It outputs two 5's (not 5.1's). This is bad for lots of reasons. First, abs
is such a natural and common function that I use it all the time, but the int
part is almost never what I want returned. Second, it's much too easy for me (or people using my code) to just write abs
and not notice that it compiles but does the wrong thing, because I'm (they're) really good at overlooking warnings. Third, I just plain don't understand why iostream bothers defining an abs
function anyway. Fourth, I really don't understand why it goes into the global namespace.
Is there any way I can prevent this objectionable abs
function from going into my global namespace?
If it matters, I'm using
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.6)
Most likely iostream
includes stdlib.h
to do some of its work. This is the C version of the header which declares abs
for int
only in the global namespace (in C you had to use fabs
for double
values).
I'm not aware of any specific way to keep abs
from being included that way but I do know that g++ 4.5 is much better at not having excess stuff brought in by basic includes like iostream
and string
.
It may also be possible to get a warning that the double is being truncated to int (EDIT: yes, use -Wconversion
to warn).
这篇关于为什么iostream定义了一个abs函数,我该如何阻止它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!