C++系列-函数重载

C++系列-函数重载

函数重载

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

函数重载的条件

  • 同一个作用域下
  • 函数名相同
  • 函数参数不同
    -- 参数个数不同
    -- 参数顺序不同
    -- 参数类型不同
  • 不可以使用返回值作为重载的条件
cpp 复制代码
code:
	#include<iostream>
	using namespace std;
	void test()
	{
		cout << "void test()" << endl;
	}
	void test(int a)
	{
		cout << "void test(int a)" << endl;
	}
	void test(int a, float b)
	{
		cout << "void test(int a, float b)" << endl;
	}
	void test(float a, int b)
	{
		cout << "void test(float a, int b)" << endl;
	}
	void main()
	{
		test();
		test(100);
		test(100, 3.14);
		test(3.14, 100);
		system("pause");
	}
result:
	void test()
	void test(int a)
	void test(int a, float b)
	void test(float a, int b)

函数重载注意事项

引用作为重载

  • 参数可以分为const和非const。
cpp 复制代码
code:
    #include<iostream>
   using namespace std;
   void test(int &a)
   {
   	cout << "void test(int &a)" << endl;
   }
   void test(const int& a)
   {
   	cout << "void test(const int& a)" << endl;
   }
   void main()
   {
   	int a = 10;
   	test(a);
   	test(10);		// 当执行void test(int &a) 则为int &a=10,会出错,const int& a=10,正常
   	system("pause");
   }
result:
void test(int &a)
void test(const int& a)

函数重载遇到默认参数

cpp 复制代码
code:
#include<iostream>
using namespace std;

void test(int a, int b = 10)
{
	cout << "void test(int a, int b = 10)" << endl;
}
void test(int a)
{
	cout << "void test(int a)" << endl;
}

void main()
{
	//test(666);		// 报错,不知道执行哪一个
	test(20, 30);
	system("pause");
}

result:
	void test(int a, int b = 10)
相关推荐
aaaweiaaaaaa2 分钟前
c++基础学习(学习蓝桥杯 ros2有C基础可看)
c++·学习·蓝桥杯·lambda·ros2·智能指针·c++类
一拳一个呆瓜24 分钟前
【MFC】对话框属性:字体 (Font Name) 和 大小 (Font Size)
c++·mfc
郝学胜-神的一滴36 分钟前
基于OpenGL封装摄像机类:视图矩阵与透视矩阵的实现
c++·qt·线性代数·矩阵·游戏引擎·图形渲染
啊?啊?1 小时前
14 C++ STL 容器实战:stack/list 模拟实现指南 + priority_queue 用法及避坑技巧
c++·
汉克老师1 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(4、最大空白区)
c++·算法·蓝桥杯·蓝桥杯c++·c++蓝桥杯
羚羊角uou2 小时前
【Linux】匿名管道和进程池
linux·c++·算法
曙曙学编程2 小时前
stm32——独立看门狗,RTC
c语言·c++·stm32·单片机·嵌入式硬件
励志不掉头发的内向程序员2 小时前
C++进阶——多态
开发语言·c++·学习
楼田莉子3 小时前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
dragoooon343 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法