c++ - Visual C++ 中的函数重载

标签 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;
}

我在双腹肌和长腹肌功能上有问题

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

为什么会出现这个问题? 我已将编译从 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);
}

输出是hellothere

最佳答案

您的问题来自一个 header ,其中为某些类型(例如 double)声明了 abs。您不能使用完全相同的 header (即相同的返回类型、相同的名称、相同的参数列表、相同的限定符,例如 const)。

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

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

第三种方法,即删除 using namespace std 根据您的评论不起作用。这是因为您包含了 Windows.h。这本身包括一堆 header ,可能包括 math.h。这在 global 命名空间中提供了一个名为 abs 的方法。如果需要,最好不要包含 Windows.h 并包含 cmath。然后,abs 仅在命名空间 std 中声明,因此您可以使用 std::abs 调用它,并且不同于 abs.

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

相关文章:

c++ - 'operator=' 已弃用:改用 QDir::setPath()

c++ - 更改刻度间隔以使用一小时增量?

c++ - 如何使用KDTree进行任意维度的top-k查询和范围查询

c++ - 如何从 XCode 编译的命令行可执行文件中重定向 STDOUT?

c++ - : int (*b)[100]是什么意思

c++ - 为什么 stack<const string> 不能在 g++ 中编译?

c# - 从 c# COM dll 返回时,C++ SAFEARRAY 具有无效数据

c++ - 指定命令参数以在用户固定我的应用程序时运行应用程序

c++ - 从继承类实现抽象方法

c++ GMP mpz_init() 导致段错误 11