c++学习13 -- 函数

#include <iostream>
using namespace std;

void fun(int a = 12 , char c = 'c') //设置函数默认参数--全部指定
{
    cout << a << ' ' << c << endl;
}

void fun1(int a , char c , float f = 123.123) //部分指定 从右向左连续、逐个指定 [ void fun1(int a = 12 , char c , float f = 123.123) 是错误的。]
{
    cout << a << ' ' << c << ' ' << f << endl;    
}


//使用写在主函数后面函数,需要先声明
void fun2(int a , char c , float f = 123.123); //默认值在声明函数的时候指定

int main()
{
    //函数调用,有默认值的函数,可以不用传递实参
    fun();

    //无默认值的,一定要传递实参
    fun1(120,'x');
    //or
    fun1(123,'y',32.2);

    fun2(222,'z');

    system("pause");
    return 0;
}

//写在主函数后面的函数
void fun2(int a , char c , float f) //写在主函数后面的函数不需要再次指定默认值,否则会出现错误报警:函数重定义
{
    cout << a << ' ' << c << ' ' << f << endl;    
}

函数重载

#include <iostream>
using namespace std;

#if 0
函数的重载
定义:
    1、在同一个作用域内
    2、函数名字相同
    3、参数列表不同(参数烈性不同、参数个数不同)
#endif

void fun(int a)
{
    cout << "1:" << a << endl;
}

void fun(int a , char b)
{
    cout << "2:" << a  << ' ' << b << endl;
}

void fun(float c)
{
    cout << "3:" << c << endl;
}

//符合条件之后,以上互为重载函数

int main()
{
    //调用,系统会根据参数的形式or个数,找到需要调用的函数
    fun(1);
    fun(2,'a');
    fun(3.3f); //因为是float类型,需要加上f,不然默认的是double类型

    system("pause");
    return 0 ;
}
原文地址:https://www.cnblogs.com/mohu/p/8966726.html