输入输出、缺省参数及函数重载

文章详细介绍了C++中的输入输出操作,包括cin和cout的使用;缺省参数的两种形式:全缺省和半缺省参数,并通过实例展示了如何使用;以及函数重载的概念,强调了通过参数列表的不同来实现同名函数的不同功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、数入、输出

#include <iostream>
using namespace std;

//1、输入、输出
int main()
{
	int i;
	double d;

	//特点:自动识别类型
	cin >> i >> d;

	cout << i << " ";
	cout << d << endl;

	cout << "Hello,bit" << endl;
	return 0;
}

2、缺省参数

void Func(int a = 0) //这里的缺省值为:0,相当于个备胎[当函数没有传值过来时,0就发挥了作用]。
{
	cout << a << endl;
}

int main()
{
	Func(1);
	Func(2);
	Func(3);
	Func();

	return 0;
}

2.1 全缺省参数

//(1)全缺省参数
void TestFunc(int a = 10, int b = 20, int c = 30)
{
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	cout << "c=" << c << endl;
	cout << endl;
}

int main()
{
	TestFunc();
	TestFunc(1);
	TestFunc(1, 2); //传参只能 从左往右且连续
	TestFunc(1, 2, 3);

	return 0;
}

2.2 半缺省参数

//(2)半缺省参数
// A 基础知识
void TestFunc(int a, int b = 20, int c = 30) //缺省只能 从右往左且连续
{
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
	cout << "c=" << c << endl;
	cout << endl;
}

int main()
{
	TestFunc(1);
	TestFunc(1, 2);
	TestFunc(1, 2, 3);

	return 0;
}

// B 具体应用
struct Stack
{
	int* a;
	int top;
	int capacity;
};

void StackInit(struct Stack* ps, int capacity = 4)
{
	ps->a = (int*)malloc(sizeof(int) * capacity);
	//......
	ps->top = 0;
	ps->capacity = capacity;
}

int main()
{
	//当知道最后需要插入100个数据,就传参100;提前开好空间,避免后面的扩容消耗
	struct Stack st1;
	StackInit(&st1, 100);

	//当不知道最后要插入多少个数据时,就不传参;缺省值4发挥作用,进行开辟空间的初始化
	struct Stack st2;
	StackInit(&st2);

	return 0;
}

//C 当存在 函数的申明与定义时,规定缺省参数要在函数申明(.h)中,函数定义(.cpp)中不需要。

3、函数的重载(一个函数具有多重作用)

//C++允许在 同一作用域 内申明几个功能类似的 同名函数;且这些同名函数必须满足形参列表(参数个数 或类型 或顺序)不同,来处理
//功能类似、数据类型不同的问题。【通过 参数的不同 来区分 同名但不同功能 的几个函数】

//A 参数的类型不同
int Add(int a, int b)
{
	return a + b;
}
double Add(double a, double b)
{
	return a + b;
}

int main()
{
	cout << Add(1, 2) << endl;
	cout << Add(1.1, 2.2) << endl;

	return 0;
}

//B 参数的顺序不同(不同类型参数的顺序不同)
void Func(int a, double b)
{
}
void Func(double a, int b)
{
}

int main()
{
	Func(1, 2.2);
	Func(1.1, 2);

	return 0;
}

//C 具体应用
//函数重载的意义就是让用的地方很方便,就像用同一个函数一样。

void Swap(int& r1, int& r2)
{
	int tmp = r1;
	r1 = r2;
	r2 = tmp;
}

void Swap(double& r1, double& r2)
{
	double tmp = r1;
	r1 = r2;
	r2 = tmp;
}

int main()
{
	int a = 1, b = 2;
	double c = 1.1, d = 2.2;
	Swap(a, b);
	Swap(c, d); //函数(Swap)重载,根据参数的类型不同来判断

	cout << a << endl;
	cout << c << endl; //函数(Cout)重载,根据参数的类型不同来判断

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值