栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++函数提高篇(默认参数,占位参数,函数重载)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++函数提高篇(默认参数,占位参数,函数重载)

函数默认参数

C++函数中的形参列表中的形参是可以有默认值的

语法:返回值类型 函数名(参数 = 默认值){}

注意事项:

  1. 如果我们自己传入数据,就用自己的数据,如果没有,就用默认值
  2. 如果某个位置参数有默认值,那么从这个位置往后,从左往右,必须都要有默认值
  3. 如果函数声明有默认参数,函数实现就不能有默认参数,声明和实现只能有一个有默认参数
#include
using namespace std;

//函数默认参数
//如果我们传入数据,则会使用我们自己的数据
//如果没有传入数据,则会使用默认值
//注意事项:从第一个默认值位置开始往后,从左到右都必须有默认值
//          如果函数声明有默认值,函数实现就不能有默认值
int test(int a,int b = 1,int c = 2)
{
	return a + b + c;
}

int main()
{

	cout << "a+b+c = " << test(10,20,30) << endl;

	system("pause");
	return 0;
}

a+b+c = 60

函数占位参数

C++函数中的形参列表里可以有占位参数,用来占位,调用函数时必须填补此位置

语法:返回值类型 函数名(数据类型){ }

#include
using namespace std;

//占位参数
//占位参数还可以有默认值
void test(int a,int = 10)
{
	cout << "this is test" << endl;
}

int main()
{
	test(10,20);

	system("pause");
	return 0;
}

this is test

函数重载概述

作用:函数名可以相同,提高函数复用性

函数重载满足条件:

  • 同一个作用域下
  • 函数名称相同
  • 函数参数 类型不同或者个数不同或者顺序不同

注意:函数返回值不可以做为函数重载的条件 即结构体前面所写的返回值类型

#include
using namespace std;

//函数重载
//函数重载满足条件
// 1、同一个作用域下
// 2、函数名称相同
// 3、函数参数 类型不同或者个数不同或者顺序不同
//函数参数 
void test()
{
	cout << "test的调用" << endl;
}

void test(int a)
{
	cout << "test(int a)的调用" << endl;
}

void test(double a)
{
	cout << "test(double a)的调用" << endl;
}

void test(int a,double b)
{
	cout << "test(int a,double b)的调用" << endl;
}

int main()
{
	test();
	test(10);
	test(3.14);
	test(10, 3.14);

	system("pause");
	return 0;
}

test的调用
test(int a)的调用
test(double a)的调用
test(int a,double b)的调用

函数重载注意事项
  • 引用作为重载条件
  • 函数重载碰到函数默认值
#include
using namespace std;

//函数重载的注意事项
//1、引用作为重载条件
void test(int &a)       //int &a = 10 不合法
{
	cout << "test的调用" << endl;
}

void test(const int &a) //const int & = 10 合法
{
	cout << "test(const int &a)的调用" << endl;
}

//2、数重载碰到函数默认值 
void test1(int a,int b = 10)
{
	cout << "test1的调用" << endl;
}
void test1(int a)
{
	cout << "test1(int a)的调用" << endl;
}
int main()
{
	int a = 10;
	test(a);
	test(10);
    //test1(10) //当函数重载碰到默认参数,出现二义性,报错,尽量避免这种情况
	test1(10, 20);
	system("pause");
	return 0;
}

test的调用
test(const int &a)的调用
test1的调用

碰到默认参数,容易产生歧义,即传入一个数据时能运行多个函数,所以我们需要避免这种情况

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/864225.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号