一、函数重载
1.1 重载概念
引入:
比如:如果我们现在想要写一个函数 , 求两个整数的和 :
#include <cstdio> #include <iostream> using namespace std; int IntAdd(int x, int y) { return x + y; } int main() { int a, b; cin >> a >> b; int r = IntAdd(a, b); cout << r << endl; return 0; }
复制
如果我们还想实现两个浮点数的和呢?
#include <cstdio> #include <iostream> using namespace std; int IntAdd(int x, int y) { return x + y; } float FloatAdd(float x, float y) { return x + y; } int main() { int a, b; cin >> a >> b; int r = IntAdd(a, b); cout << r << endl; float c, d; cin >> c >> d; float f = FloatAdd(c, d); cout << f << endl; return 0; }
复制
那 .. 还有double , 还有....
我们发现 , 这些都是功能相似 , 只是类型不同 ; C++ 引入了函数重载的功能 ,对于这种情况 , 可以只使用一个函数名 来实现不同类型的变量相加 , 大大减少了我们的记忆成本和代码的冗余。
函数重载 : C++ 中的函数重载是指在 同一个作用域中可以有多个同名函数 , 它们的函数名称相同 , 但是参数列表不同 。
函数返回类型 函数名(参数1 , 参数 2 , .... )
1 ) 不同 : 参数的数量 , 类型和顺序至少有一个不同 ;
2 )函数的返回类型并不影响函数的重载 , 因为C++编译器 不会 根据返回类型来区分不同函数。
1.2 重载举例
#include <cstdio> #include <iostream> using namespace std; //1.参数类型不同 int Add(int x, int y) { return x + y; } float Add(float x, float y) { return x + y; } //2.参数数量不同 void f() { cout << "f()" << endl; } void f(int a) { cout << "f(int a)" << endl; } //3.参数顺序不同 void f(int a, char b) { cout << "f(int a, char b)" << endl; } void f(char b, int a) { cout << "f(char b, int a)" << endl; } int main() { Add(10, 20); Add(1.1f , 2.2f); f(); f(10); f(10, 'a'); f('a',10); return 0; }
复制
二、函数练习
练习一:简单算术表达式求值
B2130 简单算术表达式求值 - 洛谷
#include <iostream> #include <cstdio> using namespace std; int calc(int x , char y , int z) { switch(y) { case '+': return x + z; case '-': return x - z; case '*': return x * z; case '/': return x / z; case '%': return x % z; } } int main() { int a = 0 , b = 0; char c = 0; cin >> a >> c >> b; int ret = calc(a,c,b); cout << ret << endl; return 0; }
复制
也可以用scanf , 但是%c 前面加个空格 , 表示忽略空白字符 :
#include <iostream> #include <cstdio> using namespace std; int calc(int x , char y , int z) { switch(y) { case '+': return x + z; case '-': return x - z; case '*': return x * z; case '/': return x / z; case '%': return x % z; } } int main() { int a , b ; char c ; scanf("%d %c%d",&a , &c , &b); int ret = calc(a,c,b); cout << ret << endl; return 0; }
复制
碎碎念:说实话 , 如果%c前面不加空格 , 这道题其实也可以过,是因为后台测试组可能只是在题目吓唬吓唬你 , 测试点并没有空格;
练习二:最大数 max(x,y,z)
B2129 最大数 max(x,y,z) - 洛谷
#include <iostream> #include <cstdio> using namespace std; int max(int x , int y , int z) { int m = x > y ? x : y; if(m < z) m = z; return m; } int main() { int a,b,c; cin >> a >> b >> c; double ret = max(a,b,c) * 1.0 / (max(a+b,b,c)*max(a,b,b+c)); printf("%.3lf\n",ret); return 0; }
复制
拓展学习:库函数max 和 min
1)max
1 . 在 C++ 中, max 函数用于返回两个值中的较大值。它是 C++ 标准库 <algorithm> 头文件中的⼀个函数。