我在Visual C++ 2010中編寫函數重載程序。 以下是我的代碼在Visual C++中重載函數
// 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;
}
我有雙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
爲什麼這個問題來了問題? 我已經將編譯從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
您可能與'std :: abs'發生名稱衝突。嘗試命名它'absoluteValue'或別的東西,或者刪除'using namespace std;'並明確地寫'std :: cout'。 – stefan
當我改變函數的名稱,然後它的工作,但那麼重載的重點是什麼。此外,我刪除命名空間,並寫了std :: cout,但仍然無法正常工作。 – Freedom911
@ MsFreedom911,使用命名空間,你將擺脫這樣的問題,它是如此簡單 – SpongeBobFan