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)
相关推荐
成工小白1 小时前
【C++ 】智能指针:内存管理的 “自动导航仪”
开发语言·c++·智能指针
sc写算法1 小时前
基于nlohmann/json 实现 从C++对象转换成JSON数据格式
开发语言·c++·json
SunkingYang1 小时前
C++中如何遍历map?
c++·stl·map·遍历·方法
Andrew_Xzw1 小时前
数据结构与算法(快速基础C++版)
开发语言·数据结构·c++·python·深度学习·算法
库库的里昂1 小时前
【C++从练气到飞升】03---构造函数和析构函数
开发语言·c++
momo卡1 小时前
MinGW-w64的安装详细步骤(c_c++的编译器gcc、g++的windows版,win10、win11真实可用)
c语言·c++·windows
凤年徐4 小时前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表
oioihoii4 小时前
C++11 右值引用:从入门到精通
开发语言·c++
木子.李3478 小时前
排序算法总结(C++)
c++·算法·排序算法
freyazzr9 小时前
C++八股 | Day2 | atom/函数指针/指针函数/struct、Class/静态局部变量、局部变量、全局变量/强制类型转换
c++