用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 = ;
int y = ;
double n = 5.0 ;
double m = 2.0; cout << operate (x,y) << '\n';
cout << operate (n,m) << '\n'; return ;
}
打印结果
2.5
Program ended with exit code:
函数模板
#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 = ;
int j = ;
int k = ;
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 ;
}
打印结果
2.5
Program ended with exit code:
模板自动匹配
#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.0))
cout << "x and y are equal\n";
else
cout << "x and y are not equal\n";
return ;
}
打印结果
x and y are equal
Program ended with exit code:
带参数的模板
#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, >() << '\n';
std::cout << fixed_multiply<int, >() << '\n';
}
打印结果
Program ended with exit code: