
inline 函數定義經常重複的小型工作模組,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | inline int max(int a, int b) { |
| 004 | return a > b ? a : b; |
| 005 | } |
| 006 | |
| 007 | int main() { |
| 008 | std::cout << max(55, 22) |
| 009 | << std::endl; |
| 010 | std::cout << max(2, 214) |
| 011 | << std::endl; |
| 012 | |
| 013 | return 0; |
| 014 | } |
| 015 | |
| 016 | /* Kaiching Chang |
| 017 | u0807.cpp |
| 018 | 2014-02 */ |
這裡定義了一個 inline 函數,工作為判斷兩個參數的大小,並且回傳較大值
| 003 | inline int max(int a, int b) { |
| 004 | return a > b ? a : b; |
| 005 | } |
編譯器 (compiler) 會將 inline 函數的部份最佳化,通常會把 inline 函數的程式直接插入執行檔編譯,避免過多的函數呼叫,因此上例會變成
| std::cout << 55 > 22 ? 55 : 22 | |
| << std::cout; | |
| std::cout << 2 > 214 ? 2 : 214 | |
| << std::cout; |
所以 inline 函數的目的除了提高效能外,也在於提供一個符合語意的名稱,此例編譯執行結果如下
| $ g++ u0807.cpp |
| $ ./a.out |
| 55 |
| 214 |
| $ |
通常 inline 函數的定義宣告會直接放在標頭檔之中。
continue ...
沒有留言:
張貼留言