zoukankan      html  css  js  c++  java
  • 【C/C++】函数的默认参数/函数的占位参数/函数重载/注意事项

    1. 函数的默认参数
      返回值类型 函数名(参数=默认值){}
    #include <iostream>
    using namespace std;
    
    int func(int a = 10, int b = 10)
    {
       return a + b;
    }
    
    int main()
    {
       int a = func(20,30);
       cout << a << endl;
       system("pause");
    }
    

    没有用默认值,有的话用输入值。

    注意:
    1. 如果某个位置参数有默认值,那么从这个位置往后,从左往右,都必须要有默认值
    2. 如果函数声明有默认值,函数实现的时候就不能有默认参数。
    
    1. 函数的占位参数
    #include <iostream>
    using namespace std;
    
    //占位参数
    //返回值类型 函数名(数据类型){}  <-没有变量名
    
    //占位参数可以有默认参数
    void func(int a, int = 10)
    {
       cout << "This is func" << endl;
    }
    
    int main()
    {
       func(10);
       system("pause");
    }
    
    1. 函数重载
      函数重载满足条件:
      ·同一个作用域下
      ·函数名称相同
      ·函数【参数】的【类型不同】 或者 【个数不同】 或者 【顺序不同】
    #include <iostream>
    using namespace std;
    
    //函数重载
    //可以让函数名相同,提高复用性
    
    //函数重载的满足条件
    //1.同一个作用域下
    //2.函数名称相同
    //3.函数【参数】【类型】不同,或者【个数】不同,或者【顺序】不同
    void func()
    {
       cout << "This is func" << endl;
    }
    
    void func(int a)
    {
       cout << "This is func22" << endl;
    }
    
    void func(double b)
    {
       cout << "This is func33" << endl;
    }
    
    int main()
    {
       func();
       func(10);
       func(2.0);
       system("pause");
    }
    
    1. 函数重载的注意事项
    #include <iostream>
    using namespace std;
    
    //函数重载的注意事项
    //1、引用作为重载的条件
    void fun(int& a) //int& a = 10;
    {
       cout << "aaa" << endl;
    }
    
    void fun(const int& a) //const int& a = 10;
    {
       cout << "aaa22" << endl;
    }
    
    //2、 函数重载碰到默认参数
    void func2(int a, int b = 10;)
    {
       cout << "bbb" << endl;
    }
    
    void func2(int a)
    {
       cout << "bbb" << endl;
    }
    
    int main()
    {
       // int a = 10;
       // fun(a);
       fun(10);
       //func2(10); //函数重载碰到默认参数,可以被调入两种,有二义性,编译错误
       system("pause");
    }
    
  • 相关阅读:
    Palindrome Linked List 解答
    Word Break II 解答
    Array vs Linked List
    Reverse Linked List II 解答
    Calculate Number Of Islands And Lakes 解答
    Sqrt(x) 解答
    Find Median from Data Stream 解答
    Majority Element II 解答
    Binary Search Tree DFS Template
    188. Best Time to Buy and Sell Stock IV
  • 原文地址:https://www.cnblogs.com/kinologic/p/14041448.html
Copyright © 2011-2022 走看看