C++核心编程之-函数提高

函数提高

函数默认参数

在c++中,函数的形参列表中的形参是可以有默认值的。

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

注意点:1、如果某个位置参数有默认值,那么从这个位置往后,必须都要有默认值

​ 2、如果函数声明有默认值,函数实现的时候就不能有默认参数

函数占位参数

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

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

示例:

#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, 20);


	return 0;
}

函数重载

函数重载概述

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

函数重载满足条件:

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

注意:函数的返回值不可以作为函数重载的条件

示例:

#include <iostream>
using namespace std;

// 函数重载
// 可以让函数名相同,提高复用性


// 函数重载的条件
//1、同一个作用域下(这里是全局作用域)
//2、函数名字相同
//3、函数参数类型不同,或者个数不同,或者顺序不同
void func(int a)
{
	cout << "我是func (int a 的调用)" << endl;
}

void func()
{
	cout << "我是func!" << endl;
}

void func(double a)
{
	cout << "我是func (double a 的调用)" << endl;
}


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

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

// 注意事项
// 函数的返回值不可以作为函数重载的条件
//----------------------------------------------------
//int func(int b, double a)  // 这里与上面改为了int 是错误的
//{
//	cout << "我是func (int b, double a 的调用)" << endl;
//}
//----------------------------------------------------

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


	return 0;
}

查看有无语法错误技巧

函数重载注意事项

  • 引用作为重载条件
  • 函数重载碰到函数默认参数
#include <iostream>
using namespace std;

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

void func(const int& a)   
{
	cout << "函数func(int& a)的调用" << endl;
}


// 2、函数重载碰到默认参数(导致二义性)
void func2(int a, int b =10)
{
	cout << "函数func2(int a)的调用" << endl;
}

void func2(int a)
{
	cout << "函数func2(int a)的调用" << endl;
}

int main()
{ 
	int a = 10;
	func(a);   // a是变量 可读可写,所以走第一个函数(无const版本)  // const修饰的是常量,只读


	func(20);  // 这里走第二个函数(有const版本) 相当于形参 const int &a = 20;


	printf("-----------------------------------------------------------------------");

	// func2(10);  // 出现二义性,报错,尽量避免这种情况

	return 0;
}

posted @ 2023-04-11 13:28  __username  阅读(12)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。