C++基础2: 优化C函数

1. 缺省参数

什么是缺省参数

缺省参数是声明或者定义函数时为函数的参数指定一个默认值,如果函数调用时没有传入实参, 那么这个默认值会被当做实参,如下例子

函数调用时, 传入参数1, a = 1,不传入参数, 默认a = 0, 这里的a就是一个缺省参数

缺省参数的分类

缺省参数分全缺省和半缺省参数

全缺省参数: 每个参数都有默认值

#include <iostream>
using namespace std;

// 全缺省
void t2(int a = 1, int b = 2, int c = 3)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl << endl;
}

int main()
{
	t2();
	t2(10);
	t2(10, 20);
	t2(10, 20, 30);
}

半缺省参数: 部分参数带有默认值

#include <iostream>
using namespace std;

// 半缺省参数
void t3(int a, int b = 1, int c = 2)
{
	cout << a << endl;
	cout << b << endl;
	cout << c << endl << endl;
}
int main()
{
	t3(10);
	t3(10, 20);
	t3(10, 20, 30);
}

使用缺省参数的注意事项

1. 半缺省参数必须从右往左, 不能有间

2. 传入的实参必须从左往右, 不能有间隔

3. 缺省参数不能再函数声明和定义出重复出现

4. 如果函数声明与定义分离时, 在函数声明里定义缺省参数

缺省参数的应用

下面用一个实际的应用场景来说明为什么缺省参数会是C函数设计中的不足

C语言实现的栈初始化:

head.h
 #pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

#define INIT_SZ 4

typedef int STDataType;
typedef struct stack
{
	STDataType* dys;
	int capacity;
	int top;
}stack;

// 初始化
void STInit(stack* ps);
test.c
 #include "head.h"

void STInit(stack* ps)
{
	assert(ps);
	STDataType* tmp = (STDataType*)malloc(sizeof(STDataType) * INIT_SZ);
	if (NULL == tmp)
	{
		perror("STInit::malloc fail");
		return;
	}
	ps->dys = tmp;
	ps->capacity = INIT_SZ;
	ps->top = 0;
}

int main()
{
	stack st;
	STInit(&st);
}

C++用缺省参数实现的栈初始化:

head.h
 #pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

typedef int STDataType;
typedef struct stack
{
	STDataType* dys;
	int capacity;
	int top;
}stack;

// 初始化
void STInit(stack* ps, int capacity = 4); // 缺省参数 capacity
test.cpp
#include "head.h"

void STInit(stack* ps, int def_capacity)
{
	assert(ps);
	STDataType* tmp = (STDataType*)malloc(sizeof(STDataType) * def_capacity);
	if (NULL == tmp)
	{
		perror("STInit::malloc fail");
		return;
	}
	ps->dys = tmp;
	ps->capacity = def_capacity;
	ps->top = 0;
}

int main()
{
	stack st1;
	stack st2;
	// 处理未知数据个数的情况
	STInit(&st1);
	// 处理已知数据个数的情况
	STInit(&st2, 100);
}

假设已经知道要向栈内入100个数据, C语言实现的栈需要不断的扩容, 而C++ 可以用缺省参数直接初始化100个空间提高效率

即使数据个数未知, 也可以不传参用默认开辟的空间, 不够时扩容, 所以使用缺省参数会更灵活

2. 函数重载

什么是函数重载

函数重载是函数的一种特殊情况,其允许在同一域中出现同名的函数

但是这些同名函数必须满足(参数类型不同, 参数个数不同, 参数顺序不同)其中一个条件, 如下

// 1、参数类型不同
int Add(int left, int right)
{
    return left + right;
}
 
double Add(double left, double right)
{ 
    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;
}
posted @ 2023-04-20 20:27  许木101  阅读(44)  评论(0)    收藏  举报