重载函数和默认参数的函数

重载函数和默认参数的函数

代码说事

重载的参数匹配

 1 /// *重载的匹配顺序   1: 严格匹配      2: 转换匹配
 2 /// *重申 :  重载的判断依据  !形参的!  个数   类型   位置
 3 /// * 返回值类型不作为重载依据
 4 /// * 默认参数 不能用于区分重载函数
 5 
 6 #include <bits/stdc++.h>
 7 using namespace std;
 8 
 9 ///  转换  的匹配
10 double b;
11 void print(int a);
12 void print(char c);
13 //void print(double b);     ///double b can't match print(int a) ;  it present wrong
14                             ///  so,  转换匹配最好不要出现
15 
16 //int print(double b);      ///即使这句都会引起  报错
17                             // ambiguating new declaration of 'void print(double)'
18 
19 //double print(double b)    ///it present wrong
20                             ///so 返回值类型不能作为重载依据  产生二义性导致匹配失败
21 /*{
22    cout<<"double's print double  b is "<<b<<endl;
23 }*/
24 void print(int a)
25 {
26     cout<<"int a is "<<a<<endl;
27 }
28 
29 void print(double b)
30 {
31     cout<<"double b is "<<b<<endl;
32 }
33 int main()
34 {
35     b=3.1415926;
36     print(b);
37     return 0;
38 }
View Code

默认参数的匹配

///据说 默认参数函数
///若同时声明和定义 则不允许出现默认参数
/// 就是同时出现  void print();  and  void print(){ ;}  //wrong

#include <bits/stdc++.h>
using namespace std;
//void print(int a=10);   // that's true what we say at the top;
void print(int a=10)        //只有这一个 才能 默认 参数值
{
    cout<<a<<endl;
}

int main()
{
    print();  ///这样竟然输出了 10!
    return 0;
}

  默认参数的顺序匹配

 1 ///据说  默认参数只能从右向左逐渐定义  调用参数时 从左向右匹配
 2 ///       *我猜这是因为 右面的参数需要重新传值的概率比较低把
 3 
 4 /// 默认参数不能区分重载函数
 5 ///     形参的个数  类型  位置
 6 #include <bits/stdc++.h>
 7 using namespace std;
 8 
 9 
10 ///当某些类的初始化  一些变量的变化不太频繁时 可以用默认参数简化重载函数
11 print(string name  , string id , string school = "jlu")
12 {
13     cout<<name<<"   "<<id<<"   "<<school<<endl;
14 }
15 
16 
17 void print(int b,char c='P')
18 {
19     cout<<"int b and char c is "<<b<<"  "<<c<<endl;
20 }
21 ///默认参数只能从右向左逐渐定义
22 //void print(int b=1,char c)        //false
23 //{
24 //   cout<<"int b and char c is "<<b<<"  "<<c<<endl;
25 //}
26 
27 /// 默认参数不能区分重载函数
28 /*void print(int b=2,char c='Q')    ///wrong
29 {
30     cout<<"int b and char c is "<<b<<"  "<<c<<endl;
31 }
32 */
33 int main()
34 {
35     //print();  wrong
36     print(3);//true
37     string name ="liuyang" , id = "55161027";
38     print(name,id);
39     return 0;
40 }
View Code
落霞与孤鹜齐飞,秋水共长天一色
原文地址:https://www.cnblogs.com/star-and-me/p/6670183.html