- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 187字
- 2021-06-10 18:28:07
Functions and scope
The compiler will also take the scope of the function into account when looking for a suitable function. You cannot define a function within a function, but you can provide a function prototype within the scope of a function and the compiler will attempt (if necessary through conversions) to call a function with such a prototype first. Consider this code:
void f(int i) { /*does something*/ }
void f(double d) { /*does something*/ }
int main()
{
void f(double d);
f(1);
return 0;
}
In this code, the function f is overloaded with one version that takes an int and the other with a double. Normally, if you call f(1) then the compiler will call the first version of the function. However, in main there is a prototype for the version that takes a double, and an int can be converted to a double with no loss of information. The prototype is in the same scope as the function call, so in this code the compiler will call the version that takes a double. This technique essentially hides the version with an int parameter.