How does function overloading work in the following case?
The following code compiles and runs but I'm not sure what exactly is going on at a lower level. Doesn't a reference just store the address of the object being refer开发者_Python百科enced? If so, both test functions are receiving an address as a parameter? Or is the C++ implementation able to differentiate between these types in some other way?
int main() {
int i = 1;
cout << test(i) << endl;
}
char test(int &i) {
return 'a';
}
char test(int *i) {
return 'b';
}
As int&
and int*
are distinct types and i
can be treated as a int&
but not as a int*
, overload resolution is absolutely unambiguous here.
It doesn't matter at this point that references are just a somewhat cloaked kind of pointer. From a language point of view they are distinct types.
References in C++ are more akin to an alias than a pointer. A reference is not a seperate variable in itself, but it is a new "name" for an exisiting variable. In your example the first test would get called because you are passing an integer to the function. A pointer is a seperate variable that holds the address of another variable so for the second function to be called you would have to call test with a pointer. Like so.. test(&i);
While a tad confusing the operator & gets the address of a variable while a variable declared with an & like int &i
declares a reference.
you code only matches with char test(int&i)
since you are passing an int&
to the function and that can not be converted to int*
精彩评论