一、默认参数
1.声明中若有默认参数,在实现时不能添加默认参数;
2.函数包含多个形参,若前面的形参有默认值,其后面的形参也必须要有默认值;
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
int func1(int a, int b = 10, int c = 10) {
return a + b + c;
}
//1. 如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值
//2. 如果函数声明有默认值,函数实现的时候就不能有默认参数
int func2(int a = 10, int b = 10);
int func2(int a, int b) {
return a + b;
}
int main() {
cout << "ret = " << func1(20, 20) << endl; //传值若未指定,则按顺序赋值;
cout << "ret = " << func1(100) << endl;
system("pause");
return 0;
}
二、函数占位参数
C++中函数的形参列表里可以有占位参数,用来做占位,调用函数时必须填补该位置
int func1(int a,int) {
return a;
}
func1(20,20); //调用时,占位参数也需要赋值;
三、函数重载
1.函数名可以相同,提高复用性
2.条件:
同一个作用域下
函数名称相同
函数参数类型不同 或者 个数不同 或者 顺序不同
引用作为重载条件
函数重载可以使用函数默认参数
3.函数的返回值不可以作为函数重载的条件
完整code如下:
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
int default_func1(int a, int b = 10, int c = 10) {
return a + b + c;
}
//1. 如果某个位置参数有默认值,那么从这个位置往后,从左向右,必须都要有默认值
//2. 如果函数声明有默认值,函数实现的时候就不能有默认参数
int default_func2(int a = 10, int b = 10);
int default_func2(int a, int b) {
return a + b;
}
int default_func3(int a,int) {
return a;
}
//函数重载需要函数都在同一个作用域下
void func()
{
cout << "func 的调用!" << endl;
}
void func(int a)
{
cout << "func (int a) 的调用!" << endl;
}
void func(double a)
{
cout << "func (double a)的调用!" << endl;
}
void func(int a ,double b)
{
cout << "func (int a ,double b) 的调用!" << endl;
}
void func(double a ,int b)
{
cout << "func (double a ,int b)的调用!" << endl;
}
//函数返回值不可以作为函数重载条件
//int func(double a, int b)
//{
// cout << "func (double a ,int b)的调用!" << endl;
//}
//函数重载注意事项
//1、引用作为重载条件
void const_func(int &a)
{
cout << "func (int &a) 调用 " << endl;
}
void const_func(const int &a)
{
cout << "func (const int &a) 调用 " << endl;
}
//2、函数重载碰到函数默认参数
void func2(int a, int b = 10)
{
cout << "func2(int a, int b = 10) 调用" << endl;
}
void func2(int a)
{
cout << "func2(int a) 调用" << endl;
}
int main() {
cout << "ret = " << default_func1(20, 20) << endl; //传值若未指定,则按顺序赋值;
cout << "ret = " << default_func1(100) << endl;
default_func3(20,20); //调用时,占位参数也需要赋值;
int a = 10;
func();
func(10);
func(3.14);
func(10,3.14);
func(3.14 , 10);
const_func(a); //调用无const
const_func(10);//调用有const
//func2(10); //碰到默认参数产生歧义,需要避免
system("pause");
return 0;
}