引用:
int a = 10;
int &b = a;
cout << a << endl; //10
cout << b << endl; //10
引用时必须先初始化 不能 int &b;
利用引用实现数据交换
void swapMy(int &a,int &b)
{
int temp = a;
a = b;
b = temp;
}
swapMy(a,b);
如果函数的返回值是引用,这个函数的调用可以作为左值。
int &test02()
{
static int a = 10;
return a;
}
int main()
{
int &ref2 = test02();
test02() = 1000;
cout << a << ref2; //1000
}
引用的本质是一个指针常量
int &ref = a; // int *const ref = &a;
ref = 20; //*ref = 20;
常量引用
用来修饰形参 防止误操作
int &ref = 10; //error
const int &ref = 10; //right
//加上const之后 编译器自动把代码转换为 int temp = 10; int &ref = temp;
void printf(const int &value) //用const修饰形参防止函数内误操作修改了a的值
{
cout << value << endl;
}
int main()
{
int a = 10;
printf(a);
}
函数默认参数
int getsum(int a,int b = 20,int c = 30)
{
return a+b+c;
}
int main()
{
int sum = getsum(10);
cout << sum << endl; //60
}
注意事项:如果某个位置已经有了默认参数,那么从这个位置往后从左到右都必须有默认参数
如果函数声明有默认参数,函数实现就不能有默认参数
函数占位参数(本阶段用处不大)
void Print(int a,int)
{
cout << a << endl;
}
int main()
{
Print(10,10);
}
占位参数也可以有默认参数。
函数重载
void func()
{
cout << "123" << endl;
}
void func(int a)
{
cout << "123" << endl;
}
int main()
{
func(); //调用第一个函数
func(10); //调用第二个函数
}
作用:函数名可以相同,提高复用性
函数重载条件:
1.同一个作用域下
2.函数名称相同
3.函数参数类型不同 或个数不同 或顺序不同
注意:函数的返回值不可以作为函数重载的条件
函数重载的注意事项
引用作为函数重载的条件
void func(int &a)
{
cout << 123 << endl;
}
void func(const int &a)
{
cout << 123 << endl;
}
//这种写法正确 两个函数的参数类型不同
int main()
{
int a = 10;
func(a); //会调用第一个函数 因为a默认为可读可写的变量
func(10); //会调用第二个函数 因为int &a = 10不合法
}
函数重载碰到默认参数
void func(int a,int b = 10)
{
cout << 132 << endl;
void func(int a)
{
cout << 132 << endl;
}
int main()
{
func(10);//无法执行,两个函数虽然参数个数不同但是都可以调用,这种写法不正确,尽量避免
func(10,20);//执行第一个函数
}