C++学习系列(1)——函数
一:函数提高
函数的占位参数
C++中函数的形参列表里可以有占有参数,用来占位,调用函数时必须填补该位置
语法:返回值类型void 函数名func(数据类型 int) {}
目前阶段没有用到,后面笔记会有用到
占位参数可以有默认参数
#include<iostream>
using namespace std;
//占位参数
//返回值类型 函数名(数据类型){}
void func(int a,int)
{
cout << "this is func" << endl;
}
int main()
{
func(20,10);
system("pause");
return 0;
}
结果:
二:函数重载
①函数重载概述
作用:函数名可以相同,提高复用性
函数重载满足条件:
1.同一个作用域下
2.函数名相同
3.函数参数类型不同或者个数不同或者顺序不同
注意:函数的返回值不可以为作为函数重载的条件
#include<iostream>
using namespace std;
//函数重载
//可以让函数名相同,提高复用性
//重载满足的条件
//1、同一个作用域先
//2、函数名相同 func
//3、函数参数类型不同或者个数不同或者顺序不同 func(参数类型,个数,顺序)
void func()
{
cout << "func 的调用" << endl;
}
void func(int a)
{
cout << "func(int a) 的调用" << endl;
}
int main()
{
//func();
func(10);//此时调用下面的func
system("pause");
return 0;
}
②函数重载的注意事项
1.引用作为重载条件
2.函数重载碰到默认参数
#include<iostream>
using namespace std;
//函数重载的注意事项
//1、引用作为重载条件
void func(int &a)//int &a=10 不合法 可读可写
{
cout << "func(int &a)调用" << endl;
}
void func(const int &a)//const int &a=10;合法 只读不写
{
cout << "func(const int &a)调用" << endl;
}
//2、函数重载碰到默认参数
void func2(int a)
{
cout << "func2(int a)的调用" << endl;
}
void func2(int a,int b=10)
{
cout << "func2(int a,int b)的调用" << endl;
}
int main()
{
/*int a = 10;
func(a);*/
/*func(10);*/
func2(20,10); //函数重载碰到默认参数,出现二义性
system("pause");
return 0;
}