C++函数的用法注意事项

默认参数

//默认参数
int test1(int a=5,int b=6) {

	return a + b;
}

//函数声明的时候写了默认参数,函数实现的时候就不能有了,两者只能有一个
int test2(int a = 3, int b = 4);

int test2(int a,int b) {
	return a + b;
}

占位参数

//占位参数.这里没有用到
void test3(int a,int ) {

	cout << "test3"<<endl;
}

重载

/*
重点部分


函数重载:同一个作用域,函数名相同但是函数的参数类型不同或者个数、顺序不同
提高函数复用性,和Java用法类似

*/
void test4() {
	cout << "无参" << endl;

}
void test4(int a) {
	cout << "含int a" << endl;
}

void test4(double a) {
	cout << "含double a" << endl;
}

//需要注意
void test4(int& a,int b) {//int& a=10 不合法
	cout << "不含 const的引用类型 " << endl;
}

void test4(const int& a,int b) {//const int& a=10合法
	cout << "含 const 的引用类型" << endl;
}

void test4(int a, double b=3.56) {//这里出现了默认参数double b 在调用的时候可能和第一个test4冲突



}

重写

//重写的注意事项是:
/*
1)重写访问修饰符的限制一定要大于被重写方法的访问修饰符

(2)重写的参数列表一定要完全和被重写的方法相同,专否则的话不能称其为重写而是重载

(3)重写返回的类型一定要一直和被重写的方法的返回类型相同,否则不能称其为重写而是重载

(4)重写方法一定不可以抛出新的检查异常或者是比被重写方法申明更加宽泛的检查型异常
*/
int main() {
	test1(4);//result 10
	test1();//result 11
	test1(1, 2);//3

	test2();//7
	test2(5);//9
	test2(2, 2);//4

	//重载
	test4(3);
	test4();
	test4(3.67);
	test4(10, 4);//猜猜
	int temp = 10;
	test4(temp, 3);//猜猜这次

}

全部示例

#include<iostream>

using namespace std;

//默认参数
int test1(int a=5,int b=6) {

	return a + b;
}

//函数声明的时候写了默认参数,函数实现的时候就不能有了,两者只能有一个
int test2(int a = 3, int b = 4);

int test2(int a,int b) {
	return a + b;
}

//占位参数.这里没有用到
void test3(int a,int ) {

	cout << "test3"<<endl;
}

/*
重点部分


函数重载:同一个作用域,函数名相同但是函数的参数类型不同或者个数、顺序不同
提高函数复用性,和Java用法类似

*/
void test4() {
	cout << "无参" << endl;

}
void test4(int a) {
	cout << "含int a" << endl;
}

void test4(double a) {
	cout << "含double a" << endl;
}

//需要注意
void test4(int& a,int b) {//int& a=10 不合法
	cout << "不含 const的引用类型 " << endl;
}

void test4(const int& a,int b) {//const int& a=10合法
	cout << "含 const 的引用类型" << endl;
}

void test4(int a, double b=3.56) {//这里出现了默认参数double b 在调用的时候可能和第一个test4冲突



}


//重写的注意事项是:
/*
1)重写访问修饰符的限制一定要大于被重写方法的访问修饰符

(2)重写的参数列表一定要完全和被重写的方法相同,专否则的话不能称其为重写而是重载

(3)重写返回的类型一定要一直和被重写的方法的返回类型相同,否则不能称其为重写而是重载

(4)重写方法一定不可以抛出新的检查异常或者是比被重写方法申明更加宽泛的检查型异常
*/

int main() {
	test1(4);//result 10
	test1();//result 11
	test1(1, 2);//3

	test2();//7
	test2(5);//9
	test2(2, 2);//4

	//重载
	test4(3);
	test4();
	test4(3.67);
	test4(10, 4);//猜猜
	int temp = 10;
	test4(temp, 3);//猜猜这次

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥学

感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值