Visual c + +中的函数重载

Fre*_*911 3 c++

我在Visual C++ 2010中编写了一个函数重载程序.以下是我的代码

// overload.cpp : Defines the entry point for the console application.

#include<Windows.h>
#include<iostream>
#include<conio.h>

using namespace std;

//abs is overloaded in 3 types
int abs(int i);
double abs(double d);
long abs(long  f);

void main()
{
    cout<<abs(-10)<<"\n";
    cout<<abs(-11.0)<<"\n";
    cout<<abs(-9L)<<"\n";
    getch();
}
int abs(int i)
{
    cout<<"using integer abs()\n";
    return i>0? -i:i;
}
double abs(double d)
{
    cout<<"using double abs()\n";
    return d>0? -d:d;
}
long abs (long l)
{
    cout<<"using long abs()\n";
    return l>0?-l:l;
}
Run Code Online (Sandbox Code Playgroud)

我在双abs和长abs功能方面遇到问题

1>c:\users\abc\documents\visual studio 2010\projects\overload\overload\overload.cpp(22): error C2084: function 'double abs(double)' already has a body
1>c:\users\abc\documents\visual studio 2010\projects\overload\overload\overload.cpp(26): error C2084: function 'long abs(long)' already has a body
Run Code Online (Sandbox Code Playgroud)

为什么会出现这个问题?我已经将编译从c更改为c ++ 但是最近我运行了另一个程序进行重载,它运行了.我不知道怎么做?这是代码.

#include<iostream>
#include<cstdio>
#include<conio.h>
#include<cstring>
using namespace std;
void stradd(char*s1,char*s2);
void stradd(char*s1,int i);
void main()
{
    char str[80];
    strcpy(str,"hello");
    stradd(str,"there");
    cout<<str<<"\n";
    getch();
}
//concatenate a string with a "stringized "integer
void stradd(char*s1,int i)
{
    char temp[80];
    sprintf(temp,"%d",i);
    strcat(s1,temp);
}
//concatenate 2 strings
void stradd(char*s1,char *s2)
{
    strcat(s1,s2);
}
Run Code Online (Sandbox Code Playgroud)

并且输出是hellothere

ste*_*fan 5

你的问题来自一个标题,其中abs声明了某些类型,如double.您不能使用具有完全相同标头的函数(即,相同的返回类型,相同的名称,相同的参数列表,相同的限定符等const).

有两种方法可以避免这种情况:

  1. 使用标准库:std::abs很好,您不需要自己实现它
  2. 命名方法absoluteValuemyAbs任何你喜欢的方法,但不是abs

第三种方式,即删除using namespace std根据您的评论不起作用.这是因为你包括Windows.h.这本身包括一堆标题,可能包括math.h.这给出了abs全局命名空间中调用的方法.如果需要,最好不要包含Windows.h和包含cmath.然后,abs仅在命名空间中声明std,因此您可以使用它来调用它,std::abs并且与之不同abs.