C++ C++;Cosine在没有std名称空间的情况下工作-为什么?

C++ C++;Cosine在没有std名称空间的情况下工作-为什么?,c++,g++,trigonometry,C++,G++,Trigonometry,我有一个相当大的应用程序,我没有使用std名称空间,我注意到我没有包括std::cos或std::sin,但我得到了正确的结果。为什么? 一些精简代码的示例如下: #include <ctime> #include <cmath> #include <iostream> #include <vector> //#include <unistd.h> #include <fstream> #include <sstrea

我有一个相当大的应用程序,我没有使用std名称空间,我注意到我没有包括std::cos或std::sin,但我得到了正确的结果。为什么?

一些精简代码的示例如下:

#include <ctime>
#include <cmath>
#include <iostream>
#include <vector>
//#include <unistd.h>
#include <fstream>
#include <sstream>
#include <iomanip>

using std::cout;
using std::endl;

int main()
{
    double pi = 4*(atan(1));

    cout << "pi = " << pi << endl
         << "cos(pi) = " << cos(pi) << endl
         << "sin(pi) = " << sin(pi) << endl;



    return 0;
}
#包括
#包括
#包括
#包括
//#包括
#包括
#包括
#包括
使用std::cout;
使用std::endl;
int main()
{
双π=4*(atan(1));

不幸的是,库实现被允许将名称从C库转储到全局名称空间以及
std
,很多都是这样。更糟糕的是,在某些情况下,全局名称空间中只有一些重载可用,如果不指定
std
版本,会导致意外的精度损失

您应该始终使用
std
版本,但遗憾的是,没有可靠的方法来强制执行,因此您只能小心地穿过这个特定的雷区。

当您包含
时,所有函数都在
std::
。对于C头,还有一个特殊规则 允许(但不要求)实现来实现它们 在全局命名空间中可见;这是因为大多数 实现只需修改C头,类似于:

#include <math.h>
namespace std
{
    using ::sin;
    using ::cos;
    // ...
}
#包括
名称空间标准
{
罪;
使用::cos;
// ...
}
这是一种实现库而无需 必须重写所有东西,只是为了在C++中使用它 将导致所有名称也出现在全局 命名空间

从形式上讲,这是一个C++11特性;C++11之前的版本要求
仅将符号引入
std::
。实际上, 所有,或者至少大多数实现都做了类似 并将其非法引入全球市场
命名空间,所以C++11改变了标准以反映现实。

Mike Seymour的回答对您有帮助吗?是的,这就解决了问题。谢谢:)事实上,在某些情况下,只有一些重载可用(这一点我已经忘记了,尽管我被它咬了一口)。