错误:对旧声明“double-round(double)”存在歧义

error: ambiguates old declaration ‘double round(double)’

本文关键字:double 存在 歧义 double-round 声明 错误      更新时间:2023-10-16
/usr/include/i386-linux-gnu/bits/mathcalls.h:311:1: error: ambiguates old declaration ‘double round(double)’
g.cpp: In function ‘int round(double)’:
g.cpp:14:24: error: new declaration ‘int round(double)’
/usr/include/i386-linux-gnu/bits/mathcalls.h:311:1: error: ambiguates old declaration ‘double round(double)’
#include <iostream>
#include <cmath>
using namespace std;
int round(double number);
int main()
{
    double number = 5.9;
    round(number);
    return 0;
}
int round(double number)
{
    return static_cast<int>(floor(number + 0.5));
}

为什么我的编译器显示错误

这里的错误非常明显。<cmath>标头已经引入了函数double round(double),并且不能基于返回类型进行重载。是的,它是在std命名空间中定义的,但您正在执行using namespace std;(它也是实现定义的,即在注入std之前是否首先在全局命名空间中定义它(。要实现完全可移植性,您需要为函数指定一个不同的名称,或者将其粘贴在另一个命名空间中——当然,也可以使用<cmath>提供的round函数。但也要去掉using namespace std;