C ++ Function Overloading Pointers

I understand that function overloading is legal if the number of parameters is different or if the type of parameter is different.

Why is the difference in just the return type not legal?

In addition, is it legal to overload as such:

int hello(int x);
int hello(int &z);

and

int hi(int x);
int hi(int *z);
+4
source share
7 answers

There is no way for the compiler to determine which function you are trying to call, just the return value. Since the return value does not need to be caught, you can write:

hello( 1 ); // return int
hello( 2 ); // return float

This is exactly the same call from what can be seen.

Yes, this is legal, as the first hello accepts the link, and the second hello accepts the memory address. You can call it like this:

hi( myNumber );
hi( &myNumber );

Completely distinguishable.

+5

. , . , .

++ :

float func() {...};
int func() {...};

int x = func(); // OK, compiler may choose `int` version!

, ...

cout << func() + func();

? , , , .

 

. - .

+4

:

int hello(int x)   // 1
{
   return x;
}

int hello(int& x)  // 2
{
   return x;
}

int hello(int const& x) // 3
{
   return x;
}

void foo()
{
   int i = 10;
   hello(i);    // Can't disambiguate between 1 and 2
   hello(10);   // Can't disambiguate between 1 and 3
}

:

int hello(int& x)  // 4
{
   return x;
}

int hello(int const& x) // 5
{
   return x;
}

void foo()
{
   int i = 10;
   hello(i);    // Picks 4
   hello(10);   // Picks 5
}
+2

, , . ,

int z = 5; 
int y = hello (z);

, ?

int z = 5; 
int y = hi (z);
int u = hi (&z);

, . , .

+1

, ; , int x , int * z .

+1

, , , , , . , , , , .

, . hello , , , , , hello .

+1

int, int& int* , .

const, , .

int hello(int);
int hello(int) const;

You cannot overload return types because the compiler did not know which function to use in full generality, especially if the return type of the function is discarded by the caller.

0
source

Source: https://habr.com/ru/post/1536726/


All Articles