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

Aar*_*ron 7 c++ trigonometry g++

我有一个相当大的应用程序,我没有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;
}
Run Code Online (Sandbox Code Playgroud)

我已将所有标题保留在其中,我在主代码中使用它们.输出按预期返回~3.14,-1和1e-16.为什么这样做?cos和罪是在std不是吗?

我在远程unix服务器上使用g ++编译器

谢谢

Jam*_*nze 9

包含时<cmath>,声明所有函数 std::.对于C头,还有一个特殊规则,它允许(但不要求)实现使它们在全局命名空间中可见; 这是因为大多数实现都会简单地调整C头,例如:

#include <math.h>
namespace std
{
    using ::sin;
    using ::cos;
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这是实现库的一种显而易见的方式,无需重写所有内容,只需要在C++中使用它,并且它将导致所有名称也出现在全局名称空间中.

形式上,这是一个C++ 11功能; pre-C++ 11要求 <cmath>只引入符号std::.实际上,所有或至少大多数实现都做了类似上面的操作,并且非法地将它们引入到全局命名空间中,因此C++ 11改变了标准以反映现实.


Mik*_*our 7

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

你应该总是使用这些std版本,但遗憾的是没有可靠的方法来强制执行,所以你只需要仔细研究这个特定的雷区.