本文共 1535 字,大约阅读时间需要 5 分钟。
用Xcode来写C++程序[5] 函数的重载与模板
此节包括函数重载,隐式函数重载,函数模板,带参数函数模板
函数的重载
#include打印结果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打印结果using namespace std;// 模板template 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 (i, j); h = sum (f, g); // 打印输出 cout << k << '\n'; cout << h << '\n'; return 0;}
302.5Program ended with exit code: 0
模板自动匹配
#include打印结果using namespace std;template 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打印结果using namespace std;template T fixed_multiply (T val) { return val * N;}int main() { std::cout << fixed_multiply (10) << '\n'; std::cout << fixed_multiply (10) << '\n';}
2030Program ended with exit code: 0
转载地址:http://ubhtx.baihongyu.com/