首页 > 编程 > C++ > 正文

C++中函数重载实例详解

2020-05-23 13:49:13
字体:
来源:转载
供稿:网友

C++中函数重载实例详解

函数重载:

1、具有相同的名称,执行基本相同的操作,但是使用不同的参数列表。
2、函数具有多态性。
3、编译器通过调用时参数的个数和类型确定调用重载函数的哪个定义。
4、只有对不同的数据集完成基本相同任务的函数才应重载。

函数重载的优 点

1、不必使用不同的函数名
2、有助于理解和调试代码
3、易于维护代码

接下来直接上代码:

#include <iostream>  using namespace std ;   void say_hello(void) {   cout << "this is hello" << endl ;  }    //数据类型不同的重载 void say_hello(int a = 100) {   cout << "this is hotdog" << endl ;  }  int say_hello(double a ) {   cout << "this is hotpig:" << a << endl ;  } //参数个数不同的重载 int say_hello(int a, int b, int c) {   cout << "a+b+c = " << a+b+c << endl ;  }   int main(void) {   say_hello(100);   say_hello(11.11);   say_hello(1 , 2 , 3);   return 0 ; }</span> 

执行结果:

this is hotdog 
this is hotpig:11.11 
a+b+c = 6 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表