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)
相关推荐
weixin_3077791317 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
AI wins17 小时前
c++新增頭文件
c++
Shadow(⊙o⊙)17 小时前
仿muduo实现高并发服务器——事件就绪管理Channel.hpp
服务器·c++
by2099918 小时前
哈希表——快速找到数据:冲突、删除与扩容的实现
数据结构·c++·哈希算法·散列表
音草18 小时前
C++ 继承详解:从概念到菱形继承
c++
weixin_3077791319 小时前
C++代码实现MATLAB中的spectralcluster函数功能
开发语言·c++·算法·matlab
xiaoye-duck19 小时前
《C++ 项目:手写大模型接入 SDK》Trae IDE 开发环境搭建与依赖管理
c++·ide·语言模型
沫璃染墨20 小时前
《Qt从零入门系列(十四):QThread多线程详解——从线程创建到客户端阻塞处理》
开发语言·c++·笔记·qt·ui·交互·线程
草莓熊Lotso20 小时前
【C++ 基于微服务的即时通讯系统】Elasticsearch 从安装到 C++ 客户端二次封装全落地
linux·网络·数据库·c++·elasticsearch·微服务
CHPCWWHSU20 小时前
FreeCAD 源码解读:从 Property 到 Command,看一套 CAD 内核的完整闭环
c++·cad