如果重新定义sqrt函数,为什么使用std::sqrt会失败?

3
#include<iostream>

double sqrt(double);

int main()
{
    double a = std::sqrt(4.0);
    std::cout << a; 
    return 0;
}

double sqrt(double a)
{
    return 1.0;
}

我知道我首先声明了sqrt函数,但是即使我使用了std::sqrt,它仍然调用了我的sqrt函数。为什么?


无法重现。这是您的实际代码吗?使用了哪个编译器/平台? - Adrian Mole
在Windows上使用Visual Studio 2019:clang-cl编译时没有警告,并输出“2”(即调用了std::sqrt)。然而,MSVC编译器不喜欢它:错误C2169:“sqrt”:内部函数,无法定义 - Adrian Mole
该问题可以使用MSVC重现。 - anastaciu
@AdrianMole https://rextester.com/CMIEE93010 - anastaciu
我使用的是VS 2019,平台是Windows,我不知道如何检查编译器。在我的电脑上没有错误,但有C28251警告,结果是1。 - xmzhang
显示剩余3条评论
1个回答

0

在你的代码中搜索是否有using namespace std;,也许它被隐藏在其他的头文件中。


1
using namespace std; 添加到 OP 的代码中对 clang-cl 和 MSVC 没有任何影响!与我在问题评论中的结果相同。 - Adrian Mole
OP的代码存在未定义行为(请参见建议的重复问题)。 - Adrian Mole

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接