作用:函数名可以相同,提高复用性 函数重载满足条件: 同一个作用域下 函数名称相同 函数参数类型不同 或者 个数不同 或者 顺序不同 注意: 函数的返回值不可以作为函数重载的条件 例: 设计一个函数重载的程序,实现以下功能 输入两个整数,输出它们的和。 输入两个浮点数,输出它们的和。 输入两个字符串,输出它们的连接结果。 输入一个字符和一个整数,输出该字符重复该整数次的结果。 #include<iostream> using namespace std; int add(int a, int b) { return } float add( ) { return a + b; } string add(string a, string b) { return } string add(char c, int n) { string res = ""; for (int i = 0; i < n; i++) { } return res; } int main() { int a = 3, b = 5; float c = 1.2, d = 3.4; string e = "hello", f = "world"; char g = '*'; int n = 4; cout << "a + b = " << add(a, b) << endl; cout << "c + d = " << add(c, d) << endl; cout << "e + f = " << add(e, f) << endl; cout << "g * n = " << add(g, n) << endl; return 0; }
时间: 2023-11-27 22:50:18 浏览: 74
下面是实现以上功能的函数重载程序:
```c++
#include<iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
string add(string a, string b) {
return a + b;
}
string add(char c, int n) {
string res = "";
for (int i = 0; i < n; i++) {
res += c;
}
return res;
}
int main() {
int a = 3, b = 5;
float c = 1.2, d = 3.4;
string e = "hello", f = "world";
char g = '*';
int n = 4;
cout << "a + b = " << add(a, b) << endl;
cout << "c + d = " << add(c, d) << endl;
cout << "e + f = " << add(e, f) << endl;
cout << "g * n = " << add(g, n) << endl;
return 0;
}
```
其中,`add(int a, int b)` 函数实现两个整数相加,`add(float a, float b)` 函数实现两个浮点数相加,`add(string a, string b)` 函数实现两个字符串连接,`add(char c, int n)` 函数实现一个字符重复一个整数次。在 `main` 函数中分别调用这几个函数,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)