c++函数基础
#include <iostream>
using namespace std;
/*
函数进阶:
1.函数默认参数:如果传入了参数 就用传入的参数,若没有就用默认的数值
若某个位置已经有默认参数,那么从这个位置后面,从左到右必须要有默认数值,如果没有提示 默认实参不在形参列表结尾
2.若函数已经声明有默认参数 那么函数实现就不能有默认参数了 声明和实现只能有一个有默认参数 这样编译器才不会有二义性
3.函数占位参数 形参列表里面可以有占位符(数据类型int..) 用来占位 调用函数时候必须填补该位置
4.函数重载
1.作用在同一个作用域下
2.函数名字相同
3.函数参数类型不同,或者参数个数不同或者顺序不同
4.引用作为重载的条件 int& 和const int& 是函数参数不同 前者是可读可写
5.函数重载遇到默认参数的时候 尽量别写这样的 会出现问题
*/
int func(int a, int b = 2, int c = 3)
{
return a + b + c; // b = 2, c = 3 如果自己传入了b的数值为其他 那么就用b传入的参数就行
}
int func_declarationed(int a = 10, int b = 300);
int func_declarationed(int a, int b)
{
return a + b;
}
// 函数占位符 占位参数也可以有默认参数
void func_Placeholder(int a, int)
{
cout << "The function has a Placeholder int!" << endl;
}
// 以下的两个函数是函数的重载
void function()
{
cout << "这个是无参数的!" << endl;
}
void function(int a)
{
cout << "这个是函数重载多了一个参数" << endl;
}
void function(double a)
{
cout << "这个是函数重载参数类型是double和int不同" << endl;
}
// 函数重载引用
void fun(int &a)
{
cout << "this is use the address!! " << endl;
}
void fun(const int &a) // const int &a = 20
{
cout << "This is a temporary variable reference, which can be used with a specific value!!!" << endl;
}
// 函数重载遇到默认参数的时候 当给默认参数赋值时候 与出现二义性
void func2(int a, int b)
{
cout << "call func2 2 parameter!" << endl;
}
void func2(int a)
{
cout << "call func1 1 parameter!" << endl;
}
int main()
{
int res_func = func(1); // 默认参数 b, c res = 6
int res_func1 = func(1, 20); // b = 20 res = 24
cout << res_func << "\t" << res_func1 << endl;
// func_declarationed
int res = func_declarationed(10, 300);
cout << res << endl; // res = 310
int res1 = func_declarationed();
cout << res1 << endl;
// 占位参数必须要有数值 若有默认的就可以不用写
func_Placeholder(10, 20);
// 引用的重载
int a = 123;
// 调用int&参数的函数
fun(a);
// 调用const int& 因为这个是一个具体的数值
fun(20);
// 函数重载的默认参数
func2(10, 20); // call func2(int a, int b)
// 如果func2(int a, int b = 20); func2(300); 则编译器不知道去选择哪一个函数进行调用,会出现报错
return 0;
}