常量引用
作用:常量引用主要用来修饰形参,防止误操作(const)
另外:
函数的默认参数
默认值写在形参后面,一个形参为默认值,则后面的形参全为默认值;
#include<iostream>
using namespace std;
//函数默认参数
//如果自己传入数据,就用自己的数据如果没有,就用默认参数
//注意事项:
// 1.如果某个位置已经由默认参数,那么从这个位置往后,
//从左到右必须都有默认参数
//例如:int func(int a=10,int b.int c) 就是错误的
//2.如果函数声明由默认参数,函数实现不能有默认参数
//声明和实现只能有一个有默认参数
int func(int a, int b = 10, int c = 20)
{
return a + b + c;
}
int main()
{
cout << func(20) <<endl;
return 0;
}
函数占位参数
c++中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置。
函数重载
作用:函数名可以相同,提高复用性
满足条件:
同一个作用域
函数名相同
函数参数类型不同,或者个数不同或者顺序不同
函数的返回值不可以作为函数重载的条件
#include<iostream>
using namespace std;
//函数重载
//函数名称相同
//函数参数类型不同,或个数不同,顺序不同
void func()
{
cout << "新" << endl;
}
void func(int a,int b=10)
{
cout << a << "+" << b << "= ";
cout <<a+b<< endl;
}
void func(double a,int b=10)
{
cout << a << "+" << b << "= ";
cout << a + b << endl;
}
int main()
{
func() ;
func(2);
func(2, 2);
func(3.14);
func(3.14, 2);
system("pause");
return 0;
}
结果:
新
2+10= 12
2+2= 4
3.14+10= 13.14
3.14+2= 5.14
请按任意键继续. . .
函数重载注意事项:代码中有详解
#include<iostream>
using namespace std;
//引用作为重载
//int&a与const int&a不一样
void func(int &a)//int &a=10 不合法
{
cout << "调用func(int a)" << endl;
}
void func(const int& a)
{
cout << "调用func(const int a)" << endl;
}
void func2(int a)
{
cout << "调用func2(int a)" << endl;
}
void func2(int a, int b = 10)
{
cout << "调用func2(int a, int b = 10)" << endl;
}
int main()
{
int a = 10;
int& a1 = a;
func(a);//都可调用,先后顺序
func(10);//只能调用void func(const int& a)
//func2(10);错误,出现起义
func2(10, 30);//可以,两个参数
system("pause");
return 0;
}