C++学习——函数高级
2021/10/16 17:10:42
本文主要是介绍C++学习——函数高级,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.函数的默认参数
函数的形参列表中的形参可以有默认值
语法: 返回值类型 函数名 (参数=默认值){ }
#include<iostream> using namespace std; //函数默认参数 //如果我们自己传入数据就用自己的数据,否则就用默认值 int func(int a,int b,int c) { return a+b+c; } //注意事项: //1.如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须有默认值 //如:int func(int a,int b=10,int c=30.int d=40) //2.如果函数声明有默认参数,函数实现就不能有默认参数(二义性) //声明和实现只能有一个有默认参数 //int func2(int a=10,int b=20); //int func2(int a,int b) //{ // return a+b; //} int main() { //cout<<func(10,20,30)<<endl; //cout<<func(10,20)<<endl;//上方 int func(int a,int b=20,int c=30)//输出70 system("pause"); return 0; }
2.函数的占位参数
参数列表里可以有占位参数,用来做占位,调用时必须填补该位置
语法: 返回值类型 函数名(数据类型){ }
#include<iostream> using namespace std; //占位参数 //返回值类型 函数名(数据类型){ } //占位参数还可以有默认参数:void func(int a,int=10) void func(int a,int)//逗号后面的int 为占位参数 { cout<<"this is func"<<endl; } int main() { func(10,10);//对应第二个10 system("pause"); }
3.函数的重载
函数重载概述
//作用: 函数名可以相同,提高复用性
//函数重载满足条件:
//1.在同一个作用域下
//2.函数名称相同
//3.函数参数类型不同 或 个数不同 或 顺序不同
函数重载
#include<iostream> using namespace std; //函数重载满足条件: //1.在同一个作用域下:当前在全局作用域下 void func() { cout<<"func()调用"<<endl; } void func(int a) { cout<<"func(int a)调用!"<<endl; } void func(double a) { cout<<"func(double a)调用!"<<endl; } void func(int a,double b) { cout<<"func(int a,double b)调用!"<<endl; } //注意:函数的返回值不可以作为函数重载的条件 (会产生二义性,该函数与上方函数二义性) /*int func(int a,double b) { cout<<"func(int a,double b)调用!"<<endl; } */ void func(double a,int b) { cout<<"func(double a,int b)调用!"<<endl; } int main() { //func();调用第一个 //func(10);//调用第二个 //func(3.14);//调用第三个 //func(3,3.14);//调用第四个 //func(3.14,3);//调用第五个 system("pause"); return 0; }
函数重载注意事项
1)引用作为重载条件
2)函数重载碰到函数默认参数
#include<iostream> using namespace std; //1.引用作为重载条件 void func(int &a) //int &a=10;不合法 { cout<<"func(int &a)调用"<<endl; //可读可写 } void func(const int &a) //const int &a=10;合法 { cout<<"func(const int &a)调用"<<endl; //只读 } //2.函数重载碰到函数默认参数 void func2(int a,int b=10) { cout<<"func2(int a,int b)调用"<<endl; } void func2(int a) { cout<<"func2(int a)调用"<<endl; } int main() { int a=10; //func(a);//调用没有加const的 //func(10);//调用加const的 //func2(10);//调用时,func2的上下两个都可能传入,即出现二义性,报错,因此使用重载尽量少使用默认参数 system("pause"); return 0; }
这篇关于C++学习——函数高级的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-21拼接的xml报文,尖括号都被转移成了< 是什么原因-icode9专业技术文章分享
- 2024-09-21Svg Sprite Icon教程:从入门到实践
- 2024-09-21Svg Sprite Icon实战:从入门到上手
- 2024-09-20构建一个多PDF RAG聊天机器人:使用Langchain和Streamlit及代码
- 2024-09-20whatsapp webhook 回调的签名验证偶尔会失败是什么原因-icode9专业技术文章分享
- 2024-09-19Excel数据导出课程:初学者必备教程
- 2024-09-19Excel数据导入课程:新手入门指南
- 2024-09-19RBAC的权限管理入门教程
- 2024-09-19如何使用Svg Sprite Icon制作图标
- 2024-09-19uniapp 如何实现点赞后全局更新数据-icode9专业技术文章分享