缺省参数(默认参数)
void Func(int a = 0)
{
cout<<a<<endl;
}
int main()
{
Func(); // 没有传参时,使用参数的默认值
Func(10); // 传参时,使用指定的实参
return 0;
}
全缺省
void Func(int a = 10, int b = 20, int c = 30)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
半缺省
void Func(int a, int b = 10, int c = 20)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
可用于动态栈补充(假设知道有多少数据时)直接传参,不知道要插入多少数据时就不传
struct Stack
{
int* a;
int top;
int capacity;
};
void StackInit(struct Stack* pst, int defaultCapacity = 4)
{
pst->a = (int*)malloc(sizeof(int) * defaultCapacity);
if (pst->a == NULL)
{
perror("malloc fail");
return;
}
pst->top = 0;
pst->capacity = defaultCapacity;
}
#define DEFAULT_CAPACITY 100
void StackInit(struct Stack* pst)
{
pst->a = (int*)malloc(sizeof(int) * DEFAULT_CAPACITY);
if (pst->a == NULL)
{
perror("malloc fail");
return;
}
pst->top = 0;
pst->capacity = DEFAULT_CAPACITY;
}
#include"Stack.h"
void StackInit(struct Stack* pst, int defaultCapacity = 4 );
int main()
{
struct Stack st1;
StackInit(&st1, 100);
//插入100个数据
struct Stack st2;
StackInit(&st2); -> StackInit(&st2, 4);
//不知道要插入多少数据
return 0;
}
函数声明和定义时不能重复定义缺省参数
声明:void StackInit(struct stack*pst,int defaultCapacity=4);
定义:void StackInit(struct stack*pst,int defaultCapacity=4)
{
;
}
因为有可能你两处定义的值不一样,不知道选用哪一个值;
//a.h
void Func(int a = 10);
// a.cpp
void Func(int a = 20)
{}
// 注意:如果生命与定义位置同时出现,恰巧两个位置提供的值不同,那编译器就无法确定到底该
用那个缺省值。
要在声明中定义缺省参数,不然预处理编译阶段看不到定义,只能在链接时看到定义
声明:void StackInit(struct stack*pst,int defaultCapacity=4);
函数重载 (有歧义,才能构成重载)
函数名相同,返回值不同不构成重载;(返回值没有进入函数名修饰规则),哪怕修改函数名修饰规则也无法构成重载,在编译时就会报错。
int Func();
double Func();
int main()
{
Func(); // 调用歧义
return 0;
}
参数类型不同,个数不同,类型顺序不同才能构成重载
#include<iostream>
using namespace std;
// 1、参数类型不同
int Add(int left, int right)
{
cout << "int Add(int left, int right)" << endl;
return left + right;
}
double Add(double left, double right)
{
cout << "double Add(double left, double right)" << endl;
return left + right;
}
// 2、参数个数不同
void f()
{
cout << "f()" << endl;
}
void f(int a)
{
cout << "f(int a)" << endl;
}
// 3、参数类型顺序不同
void f(int a, char b)
{
cout << "f(int a,char b)" << endl;
}
void f(char b, int a)
{
cout << "f(char b, int a)" << endl;
}
int main()
{
Add(10, 20);
Add(10.1, 20.2);
f();
f(10);
f(10, 'a');
f('a', 10);
return 0;
}
特殊样例
1.构成重载
2.无参调用存在歧义
void f()
{
cout<<"f()"<<end1
}
void f(int a=0)
{
cout<<"f(int a)"<<end1;
}
int main()
{
f();//构成重载,但是不知道调用哪一个,对重载函数的调用不明确
}
为什么C语言不支持重载,Cpp支持重载,cpp怎么支持的呢
1.编译链接过程
预处理:头文件展开/宏替换/条件编译/去掉注释
生成.i文件
编译:检查语法,生成汇编代码(编译错误)
生成.s文件
汇编:汇编代码转换成二进制机器码
生成.o文件
链接(链接错误)
可执行程序:xxx.exe/a.out
c语言符号表记录的是函数名,cpp记录的是函数地址
2.函数名修饰规则
链接时,参数不同,修饰出来的符号表函数名不同
C语言汇编代码
CPP汇编代码
实参类型不一样,函数名在编译阶段发生改变
_Z为默认前缀,数字代表原函数名长度,加原函数名,加类型名