#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;
}
这个程序打印的结果是什么呢?通过程序运行可以看到打印的结果是:
cpp复制代码
ret1:75
ret2:180
通过这个程序的运行你大概知道缺省参数是个什么东西了吧!再来一个代码:
cpp复制代码
#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;
}
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;
}
但是有了缺省参数我们便可以一步搞定了,一开始想开多大就开多大。代码如下:
cpp复制代码
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;
}
//引用
void swap(int& a, int& b)
{
int tmp = a;
a = b;
b = tmp;
}
int main()
{
int a = 0;
int b = 10;
cout << "swap前a:" << a << endl;
cout << "swap前b: " << b << endl;
swap(a, b);//swap函数调用
cout << endl;
cout << "swap后a:" << a << endl;
cout << "swap后b: " << b << endl;
return 0;
}