C++Note 函数重载

函数重载概述

作用:函数名可以相同,提高复用性

函数重载满足条件:

**同一个作用域下

**函数名称相同

**函数参数类型不同  或者  个数不同  或者  顺序不同

注:函数的返回值不可以作为函数重载的条件

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 
 4 //函数重载:可以让函数名相同,提高复用性
 5 //1.同一个作用域下
 6 //2.函数名称相同
 7 //3.函数的参数类型不同 或者个数不同 或者顺序不同
 8 void func()
 9 {
10     cout << "func的调用" << endl;
11 }
12 void func(int a)
13 {
14     cout << "func(int a)的调用" << endl;
15 }
16 void func(double a)
17 {
18     cout << "func(double a)的调用" << endl;
19 }
20 void func(int, double)
21 {
22     cout << "func(int,double)的调用" << endl;
23 }
24 
25 void func(double, double)
26 {
27     cout << "func(double, double)的调用" << endl;
28 }
29 //int func(double, double) // int void 二义性
30 //{
31 //    cout << "func(double, double)的调用" << endl;
32 //}
33 // 注意:函数的返回值不可以作为函数重载的条件
34 int main() 
35 {
36     func();
37     func(1);
38     func(3.1);
39     func(1, 1.1);
40     func(1.1, 2.1);
41     system("pause");
42     return 0;
43 }
复制代码

函数重载注意事项:

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 
 4 //函数重载的注意事项
 5 //1.引用作为重载的条件
 6 void func(int& a)// int &a = 10; 不合法的 
 7 {
 8     cout << "func(int &a)" << endl;
 9 }
10 void func(const int& a)//限制只读状态  const int &a = 10;合法
11 {
12     cout << "func(const int& a)" << endl;
13 }
14 //2.函数重载碰到默认参数
15 void func2(int a, int b = 10)
16 {
17     cout << "func(int a, int b)调用" << endl;
18 }
19 void func2(int a)  //与上函数有二义性    例如:func2(10)   但是func2(1,1)正确
20 {
21     cout << "func(int a)调用" << endl;
22 }
23 int main() 
24 {
25     int a = 10;
26     func(a);//int &a
27     func(10);//const int &a
28     system("pause");
29     return 0;
30 }
复制代码

 

posted on   廿陆  阅读(5)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示