Function Overloading in Visual c++ -


i writing program of function overloading in visual c++ 2010 . following code

// overload.cpp : defines entry point console application.  #include<windows.h> #include<iostream> #include<conio.h>  using namespace std;  //abs 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; } 

i having problems in double abs , long abs function

1>c:\users\abc\documents\visual studio 2010\projects\overload\overload\overload.cpp(22): error c2084: function 'double abs(double)' has body 1>c:\users\abc\documents\visual studio 2010\projects\overload\overload\overload.cpp(26): error c2084: function 'long abs(long)' has body 

why problem coming? have changed compilation c c++ but ran other program overloading,it worked.i don't know how? here code.

#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 string "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); } 

and output hellothere

your problem comes header in abs declared types such double. you're not allowed have functions same header (that is, same return type, same name, same list of parameters, same qualifiers such const).

there 2 ways of avoiding this:

  1. use standard library: std::abs good, don't need implement yourself
  2. naming method absolutevalue or myabs or whatever like, not abs

a third way, namely removing using namespace std not work according comment. because include windows.h. includes bunch of headers, including math.h. gives method called abs in global namespace. better don't include windows.h , include cmath if need to. then, abs declared in namespace std, hence can call std::abs , different abs.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -