我试图在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'
Run Code Online (Sandbox Code Playgroud)
程序
#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;
}
Run Code Online (Sandbox Code Playgroud)
我复制了与Herbert Schildt的C++ Complete Reference,Fourth Edition中给出的相同的代码
您应该删除using namespace std,因为标头abs库中已有函数cmath,或者您可以将自己的函数包装到某个名称空间中.
因此,由于您有错误math.h- 您应该使用其他函数名称,或者尝试将函数包装到您自己的命名空间中.
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |