用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) << ' '; cout << operate (n,m) << ' '; return 0; }
打印结果
10 2.5 Program 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 << ' '; cout << h << ' '; return 0; }
打印结果
30 2.5 Program 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 "; else cout << "x and y are not equal "; return 0; }
打印结果
x and y are equal Program 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) << ' '; std::cout << fixed_multiply<int, 3>(10) << ' '; }
打印结果
20 30 Program ended with exit code: 0