C++之函数重载
2019獨角獸企業重金招聘Python工程師標準>>>
C++的重載,C++的重載的兩個函數參數數量可以相同也可以不同,當參數數量相同時,只需要對應參數類型不同即稱為重載。
In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.
For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.
Another appropriate example would be a Print(object O) method. In this case one might like the method to be different when printing, for example, text or pictures. The two different methods may be overloaded as Print(text_object T); Print(image_object P). If we write the overloaded print methods for all objects our program will "print", we never have to worry about the type of the object, and the correct function call again, the call is always: Print(something).
以下程序實現了函數的重載。
#include?<stdlib.h> #include?<iostream> using?namespace?std; void?fun(int?i=30,?int?j=20,?int?k=10); int?main(void) {fun();fun(100);fun(100,?200);fun(100,?200,?300);system("pause");return?0;} void?fun(int?i,?int?j,?int?k) {cout?<<?i?<<","<<?j?<<","<<?k<<endl; }程序中,同名函數,函數參數的個數不同,注意形參默認值和函數在初始化時指定的形參的覆蓋順序是從左往右一順來的。其中,形參默認值只能對應最后一個形參。運行結果:
當參數類型不一致時,也可形成重載:
#include?<stdlib.h> #include?<iostream> using?namespace?std; void?fun(int?i=30,?int?j=20,?int?k=10);//inline?void?fun(int?i=30,?int?j=20,?int?k=10); void?fun(double?i,?double?j);//inline?void?fun(double?i,?double?j);int?main(void) {fun(1.1,?2.2);fun(1,?2);system("pause");return?0;}void?fun(int?i,?int?j,?int?k) {cout?<<?i?<<","<<?j?<<","<<?k<<endl; } void?fun(double?i,?double?j) {cout?<<?i?<<?","?<<?j?<<?endl; }運行結果:
The intent of the inline keyword is to serve as an indicator to the optimizer that inline substitution of the function is preferred over function call, that is, instead of executing the call CPU instruction to transfer control to the function body, a copy of the function body is executed without generating the call. This avoids extra overhead created by the function call (copying the arguments and retrieving the result) but it may result in a larger executable as the code for the function has to be repeated multiple times.
inline(內聯)是對編譯器編譯時的一種建議,不影響結果,只改變了編譯的效率。減小了直接調用函數時造成的開銷。不過最終生成的可執行目標文件可能會比之前大。
轉載于:https://my.oschina.net/donngchao/blog/527497
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: 管理员账户遇到“操作需要管理员权限”解决
- 下一篇: 用C++/CLI搭建C++和C#之间的桥