c++ - 在 C++ 中显示错误的函数重载示例

标签 c++

我正在尝试运行 C++ 中的函数重载示例。但它向我显示以下错误

        function.cpp(21): error C2084: function 'double abs(double)' already has a body
        include\math.h(495) : see previous definition of 'abs'
        function.cpp(26): error C2084: function 'long abs(long)' already has a body
        include\stdlib.h(467) : see previous definition of 'abs'

程序

#include<iostream>
using namespace std;

int abs(int i);
double abs(double d);
long abs(long l);
int main()
 {

     cout << abs(-10);
     cout << abs(-20.2);
     cout << abs(-30L);
     return 0;
 }

int abs(int i)
{
    cout << "Using int \n";
    return i<0 ? -i:i;
}

double abs(double d)
{
    cout << "Using Double \n";
    return d<0.0 ?-d:d;
}
 long abs(long l)
 {
     cout << "Using Long\n";
     return l<0?-l:l;
 }

我复制了 Herbert Schildt 着的 C++ Complete Reference 第四版中给出的相同代码

最佳答案

你应该删除using namespace std,因为在cmath header 的标准库中已经有abs 函数,或者你可以将您自己的函数包装到某个命名空间中。

因此,由于您有来自 math.h 的错误 - 您应该使用其他函数名称,或者尝试将函数包装到您自己的命名空间中。

关于c++ - 在 C++ 中显示错误的函数重载示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20142779/

相关文章:

c++ - 是否可以在 C++ 中使用 nmap 功能?

c++ - 用 gcc 编译 asio

c++ - boost multi_index_container 损坏的索引

c++ - 仅通过命令行在 Windows 上运行 CMake 生成的 INSTALL.vcxproj?

c++ - alglib BLEIC 优化器

c++ - 选择 QTableView 中的列时显示上下文菜单

C++ 快速排序段错误

c++ - 如何推导出执行时间增长率(大O)?

c# - 我可以在 C++ 中创建一个类似于 C# 的全局命名空间层次结构来帮助开发人员使用我们的代码吗?

c++ - 如何初始化模态对话框? (C++/MFC)