標籤:
用Xcode來寫C++程式[4] 函數
此節包括引用函數,內嵌函式,防止修改函數入參,函數自身帶有預設值.
引用函數:防止複製對象,減少系統開銷
內嵌函式:編譯的時候根據具體情形將代碼嵌入進去,成不成功編譯器說了算,減少系統開銷提升效能
引用函數(防止篡改初始值的入參聲明方式):防止修改資料來源
函數參數帶有預設值:函數的某個參數可以給定預設值,精簡函數的使用
最簡單的函數
#include <iostream>using namespace std;int addition (int a, int b) { return a + b;}int main () { int z; z = addition (5,3); cout << "The result is " << z << endl;}
列印結果
The result is 8Program ended with exit code: 0
傳遞引用(int& 表示)
#include <iostream>using namespace std;void duplicate (int& a, int& b, int& c) { a *= 2; b *= 2; c *= 2;}int main () { int x = 1, y = 3, z = 7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z << endl; return 0;}
列印結果
x=2, y=6, z=14Program ended with exit code: 0
防止篡改資料來源(const 修飾變數)
#include <iostream>#include <string>using namespace std;string concatenate (const string& a, const string& b) { return a + b;}int main () { string x = "You"; string y = "XianMing"; cout << concatenate(x, y) << endl; return 0;}
列印結果
YouXianMingProgram ended with exit code: 0
內嵌函式(減少函數調用開銷)
#include <iostream>#include <string>using namespace std;inline string concatenate (const string& a, const string& b) { return a + b;}int main () { string x = "You"; string y = "XianMing"; cout << concatenate(x, y) << endl; return 0;}
列印結果
YouXianMingProgram ended with exit code: 0
帶預設值的函數(如果不賦值,則有一個預設值)
#include <iostream>using namespace std;int divide (int a, int b = 2) { int r; r = a / b; return (r);}int main () { cout << divide (12) << endl; cout << divide (20, 4) << endl; return 0;}
列印結果
YouXianMingProgram ended with exit code: 0
函數先聲明,後使用
#include <iostream>using namespace std;void odd (int x);void even (int x);int main() { int i; do { cout << "Please, enter number (0 to exit): "; cin >> i; odd (i); } while (i!=0); return 0;}void odd (int x){ if ((x%2)!=0) cout << "It is odd.\n"; else even (x);}void even (int x){ if ((x%2)==0) cout << "It is even.\n"; else odd (x);}
遞迴調用
#include <iostream>using namespace std;long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return 1;}int main () { long number = 9; cout << number << "! = " << factorial (number); return 0;}
列印結果
9! = 362880Program ended with exit code: 0
[C++] 用Xcode來寫C++程式[4] 函數