C++核心编程:3函数提高

1函数默认参数

#include<iostream>
using namespace std;
//函数默认值
//如果我们自己传入数据,就用自己的数据,如果没有,那么用默认值
//语法:返回值类型 函数名(形参=默认值){}
int func(int a = 10, int b = 20, int c = 30)//注意事项 如果某个位置有默认值 则后面的必须都有默认值
{
	return a + b + c;
}
//2、如果函数声明有默认参数,函数实现就不能有默认值了  声明和实现只能有一个有默认参数。
int func2(int a = 10, int b = 20);//声明命名了
int func2(int a, int b)//函数实现就不能有默认值了
{
	return a + b;
}
int main1()
{
	
	int a = 20;//如果实参赋值 则形参失效。
	cout << func(a) << endl;
	cout << func2() << endl;
	system("pause");
	return 0;

}

2函数占位参数

//c++中函数的形参列表里可以有占位参数,用来做占位 调用函数时必须填补该位置。
#include<iostream>
using namespace std;
//占用参数
//返回值类型 函数名 (数据类型)
//目前阶段的占位参数用不到 后面的课程会用到的
void func(int a , int=10)//后面的占用参数  但是用不到 传入不进去   占用参数可以有默认值
{
	cout << "this is func" << endl;
}
int main2()
{
	func(10);
	system("pause");
	return 0;
}

3函数重载

//函数重载的作用:函数名可以相同 提高复用性
//函数重载满足条件:
//同一作用域下  函数名称相同 函数参数类型不同 个数不同 顺序不同
//注意:函数的返回值不可以作为函数重载的条件
#include<iostream>
using namespace std;
//满足作用域相同 都在全局作用域  函数名都是func
void func()
{
	cout << "this is func()" << endl;
}
void func(int a)//函数参数个数不同
{
	cout << "this is func(int a)" << endl;
}
void func(double a)//函数参数的类型不同
{
	cout << "this is func(float a)" << endl;
}
void func(int a, double b)//函数参数的类型不同
{
	cout << "this is func(int a,float b)" << endl;
}
void func(double b, int a)//函数参数的顺序不同  但是函数类型不同 不能重载
{
	cout << "this is func(float b, int a)" << endl;
}
int main3()
{
	func();
	func(10);
	func(3.14);
	func(10,3.14);
	func(3.14,10);
	system("pause");
	return 0;
}

4函数重载的注意事项

#include<iostream>
using namespace std;
//函数重载的注意事项
//1、引用作为重载的条件 
//类型不同
void fun(int& a)//必须传入变量 
{
	cout << "this is fun(int& a)" << endl;
}
void fun(const int& a)//必须传入常量  const 只读不写
{
	cout << "this is fun(const int& a)" << endl;
}
//2、函数重载碰到默认参数
void fun2(int a, int b = 10)
{
	cout << "this is fun2(int a, int b = 10)" << endl;
}
void fun2(int a)
{
	cout << "this is fun2(int a)" << endl;
}
int main()
{
	int a = 10;
	fun(a);
	fun(10);
	//4fun2(10);//当函数重载碰到默认参数 出现二义性 报错 尽量避免出现这种情况
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值