思维导图:
一,缺省参数
#include<iostream>
using std::cout;
using std::endl;
int Add(int a = 70, int b = 5)
{
return a + b;
}
int main()
{
int ret1 = Add();
int ret2 = Add(100, 80);
cout <<"ret1:" << ret1 << endl;
cout <<"ret2:" << ret2 << endl;
}
#include<iostream>
using std::cout;
using std::endl;
void Print(int a = 5, int b = 6, int c = 7)
{
cout << a << " ";
cout << b << " ";
cout << c << endl;
}
int main()
{
Print();
Print(9);
Print(8, 8);
Print(6, 6, 6);
return 0;
}
这段代码打印的结果是什么呢?程序运行打印结果如下:
5 6 7
9 6 7
8 8 7
6 6 6
使用缺省参数时要注意的点
缺省参数的作用
typedef struct List
{
int *a;
int size;
int capacity;
}List;
void ListInit(List* pList)
{
pList->a = NULL;
pList->size = 0;
pList->capacity = 0;
}
void PushBack(List* pList)
{
//检查是否为NULL,malloc空间
// 检查是否需要扩容,realloc
//……
}
int main()
{
List s;
ListInit(&s);
PushBack(&s);
return 0;
}
typedef struct List
{
int* a;
int size;
int capacity;
}List;
void ListInit(List* pList, int n = 4)
{
int* a = (int*)malloc(sizeof(int) * n);
pList->size = 0;
pList->capacity = n;
}
int main()
{
List s;
ListInit(&s);//不像开辟就默认开辟四个(缺省值个)空间
List p;
ListInit(&p, 100);//像开辟一百个空间就开辟一百个空间
return 0;
}
二,函数重载
函数重载的条件
比如下面的代码:
int Add(int x, double y)
{
return x + y;
}
//类型不同
int Add(int x, int y)
{
return x + y;
}
//个数不同
int Add(int x, double y, int z)
{
return x + y + z;
}
//顺序不同
int Add(double x, int y)
{
return x + y;
}
代码:
int Add(int x, double y)
{
return x + y;
}
double Add(int x, double y)
{
return x + y;
}
char Add(int x, double y)
{
return x + y;
}
//……还有很多只是返回值的类型不同的情况都不构成函数重载!
函数重载的作用
三,引用
1.引用的格式
2.引用的本质
3.引用的特点
四,使用引用的两种形式
1.引用作参数(输出型参数)
二,引用做返回值
应该传引用返回的场景
补充:利用传引用返回来修改顺序表里面的值和读取第i个位置的值。
C语言版本:
//C语言读取第i个位置的值
int Find(List* ps, int i)
{
assert(ps);
return ps->a[i];
}
//修改第i个位置的值
void SLModify(List* ps, int i, int x)
{
assert(i < ps->size);
ps->a[i] = x;
}
C++利用引用版本:
int& SLAC(List& ps,int i)
{
assert(i < ps.size);
return ps.a[i];
}
补充: