標籤:
用Xcode來寫C++程式[5] 函數的重載與模板
此節包括函數重載,隱式函數重載,函數模板,帶參數函數模板
函數的重載
#include <iostream>using namespace std;int operate (int a, int b) { return (a * b);}double operate (double a, double b) { return (a / b);}int main (){ int x = 5; int y = 2; double n = 5.0 ; double m = 2.0; cout << operate (x,y) << ‘\n‘; cout << operate (n,m) << ‘\n‘; return 0;}
列印結果
102.5Program ended with exit code: 0
函數模板
#include <iostream>using namespace std;// 模板template <class T>T sum (T a, T b) { T result; result = a + b; return result;}int main () { // 值初始化 int i = 5; int j = 6; int k = 0; double f = 2.0, g = 0.5, h; // 使用模板函數 k = sum<int>(i, j); h = sum<double>(f, g); // 列印輸出 cout << k << ‘\n‘; cout << h << ‘\n‘; return 0;}
列印結果
302.5Program ended with exit code: 0
模板自動匹配
#include <iostream>using namespace std;template <class T, class U>bool are_equal (T a, U b) { return (a == b);}int main () { // 自動模板識別 if (are_equal(10,10.0)) cout << "x and y are equal\n"; else cout << "x and y are not equal\n"; return 0;}
列印結果
x and y are equalProgram ended with exit code: 0
帶參數的模板
#include <iostream>using namespace std;template <class T, int N>T fixed_multiply (T val) { return val * N;}int main() { std::cout << fixed_multiply<int, 2>(10) << ‘\n‘; std::cout << fixed_multiply<int, 3>(10) << ‘\n‘;}
列印結果
2030Program ended with exit code: 0
[C++] 用Xcode來寫C++程式[5] 函數的重載與模板