Is this function properly overloaded?

Consider these four functions in one C ++ program:

void a(int val)
{
    cout<<val;
}
void a(int &val)
{
    cout<<val;
}
void a(int *val)
{
    cout<<val;
}
void a(double val)
{
    cout<<val;
}

A few questions that I have:

Will there be any errors in the code? or they are all overloaded without any errors. Can you tell me how to properly name all four of these functions? My attempt was below:

int iTmp; 
int *pTmp; 
double dTmp;

a(iTmp); 
a(iTmp); 
a(pTmp); 
a(dTmp);
+4
source share
5 answers

The only problem is the functions:

void a(int &val)

and

void a(int val)

The compiler will generate the following errors:

Compilation error   time: 0 memory: 3140 signal:0
prog.cpp: In function 'int main()':
prog.cpp:28:8: error: call of overloaded 'a(int&)' is ambiguous
  a(iTmp); 
        ^

Since it cannot distinguish between both, if you delete one of them, compilation succeeds

See an example:

#include <iostream>
using namespace std;

void a(int val)
{
    cout<<val;
}
void a(int *val)
{
    cout<<val;
}
void a(double val)
{
    cout<<val;
}

int main() {
    int iTmp = 0; 
    int *pTmp = 0; 
    double dTmp = 0.0;

    a(iTmp); 
    a(iTmp); 
    a(pTmp); 
    a(dTmp);
    return 0;
}

See working example:

http://ideone.com/WRZUoW

+3
source

Your code will compile but call

int iTmp; 
a(iTmp);

,

void a(int val)
{
    cout<<val;
}
void a(int &val)
{
    cout<<val;
}

.

:

[over.match.best]

F1 , F2, ICSi (F1) , ICSi (F2)

int->int
int->int&

, [over.ics.rank]p3.2 ( )

, "".

: ( ), , undefined.

+2

, .

int i = 12;
a(i);

a(int i) c(int& i) , .

void a(const int& i) { ... }

.

0

void a(int val)
{
    cout<<val;
}
void a(int &val)
{
    cout<<val;
}

a(iTmp); . . (int *val) (double val) .

0

,

  void a(int val) { 

void a(int& val) { 

iTmp.

, , , → UB ,

void a(int* val) {
   std::cout << val << std::endl;
}

, . , std::cout << *val << std::endl;, , , , ( , , (void * char *);

0
source

All Articles