#include<iostream>usingnamespace std;//1、输入、输出intmain(){int i;double d;//特点:自动识别类型
cin >> i >> d;
cout << i <<" ";
cout << d << endl;
cout <<"Hello,bit"<< endl;return0;}
2、缺省参数
voidFunc(int a =0)//这里的缺省值为:0,相当于个备胎[当函数没有传值过来时,0就发挥了作用]。{
cout << a << endl;}intmain(){Func(1);Func(2);Func(3);Func();return0;}
2.1 全缺省参数
//(1)全缺省参数voidTestFunc(int a =10,int b =20,int c =30){
cout <<"a="<< a << endl;
cout <<"b="<< b << endl;
cout <<"c="<< c << endl;
cout << endl;}intmain(){TestFunc();TestFunc(1);TestFunc(1,2);//传参只能 从左往右且连续TestFunc(1,2,3);return0;}
2.2 半缺省参数
//(2)半缺省参数// A 基础知识voidTestFunc(int a,int b =20,int c =30)//缺省只能 从右往左且连续{
cout <<"a="<< a << endl;
cout <<"b="<< b << endl;
cout <<"c="<< c << endl;
cout << endl;}intmain(){TestFunc(1);TestFunc(1,2);TestFunc(1,2,3);return0;}// B 具体应用structStack{int* a;int top;int capacity;};voidStackInit(structStack* ps,int capacity =4){
ps->a =(int*)malloc(sizeof(int)* capacity);//......
ps->top =0;
ps->capacity = capacity;}intmain(){//当知道最后需要插入100个数据,就传参100;提前开好空间,避免后面的扩容消耗structStack st1;StackInit(&st1,100);//当不知道最后要插入多少个数据时,就不传参;缺省值4发挥作用,进行开辟空间的初始化structStack st2;StackInit(&st2);return0;}//C 当存在 函数的申明与定义时,规定缺省参数要在函数申明(.h)中,函数定义(.cpp)中不需要。
3、函数的重载(一个函数具有多重作用)
//C++允许在 同一作用域 内申明几个功能类似的 同名函数;且这些同名函数必须满足形参列表(参数个数 或类型 或顺序)不同,来处理//功能类似、数据类型不同的问题。【通过 参数的不同 来区分 同名但不同功能 的几个函数】//A 参数的类型不同intAdd(int a,int b){return a + b;}doubleAdd(double a,double b){return a + b;}intmain(){
cout <<Add(1,2)<< endl;
cout <<Add(1.1,2.2)<< endl;return0;}//B 参数的顺序不同(不同类型参数的顺序不同)voidFunc(int a,double b){}voidFunc(double a,int b){}intmain(){Func(1,2.2);Func(1.1,2);return0;}//C 具体应用//函数重载的意义就是让用的地方很方便,就像用同一个函数一样。voidSwap(int& r1,int& r2){int tmp = r1;
r1 = r2;
r2 = tmp;}voidSwap(double& r1,double& r2){double tmp = r1;
r1 = r2;
r2 = tmp;}intmain(){int a =1, b =2;double c =1.1, d =2.2;Swap(a, b);Swap(c, d);//函数(Swap)重载,根据参数的类型不同来判断
cout << a << endl;
cout << c << endl;//函数(Cout)重载,根据参数的类型不同来判断return0;}