C ++ collection-function overloading, collection-function Overloading
C ++ collection-function Overloading
Preface
Function overloading does not seem difficult, but there are still some issues worth noting. The following describes several keywords:
Body 1. Scope
Several facts need to be pointed out about the scope
First, you must note that,
Function in the same scope will be overloaded.. Functions in different scopes, even with the same name, have the same parameter type and return value type. They are also two different functions.
2. Hide when the scope is nested.
# Include <iostream> using namespace std; // varint var = 0 in the global scope; void print (void) {cout <"Global print" <endl ;} int main () {// g_var in local scope will hide g_varint var = 1 in global scope; // local print will also hide global printauto print = [] (void) {cout <"local print" <endl ;}; // all the following calls are local cout <"var =" <var <endl; print (); // call the global cout <": var =" <: var <endl;: print (); cin. get (); return 0 ;}Run
Because the main function is nested inside the global scope, an object with the same name may be hidden. To call a global object, you must use the global OPERATOR ::. It should be further pointed out that hiding is only a phenomenon. In essence, it is an object name search rule. The name search rule for C ++ is as follows: from the appearance of the name to the start of the scope of the name, this section is searched. If it is found, it will not be searched. If it cannot be found, it will jump to the previous scope to continue searching. In this sample code, you can find var and print in the main function, so the call is local. Hidden phenomena indicate that functions with the same name in different scopes are not overloaded.
3. The connection between const and overload const is that the overload can only be distinguished by the underlying const.
#include <iostream>using namespace std;void print(const char *str){cout << "void print(const char *str) call" << endl;cout << str;}void print(char *str){cout << "void print(char *str) call" << endl;cout << str;}int main(){char str[] = "David";print("zhangxiang");cout << endl;print(str);cin.get();return 0;}Run
If you change void print (const char * str) to void print (char * const str), the following error occurs: error C2084: function 'void print (char * const) after compilation) 'Already has a body, that is, the top-level const cannot distinguish between overload.
Contents of this column
Directory of all contents