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)
相关推荐
郝学胜-神的一滴26 分钟前
Qt的QSlider控件详解:从API到样式美化
开发语言·c++·qt·程序人生
橘颂TA27 分钟前
【剑斩OFFER】算法的暴力美学——连续数组
c++·算法·leetcode·结构与算法
学困昇1 小时前
C++11中的{}与std::initializer_list
开发语言·c++·c++11
郝学胜-神的一滴1 小时前
Qt的QComboBox控件详解:从API到样式定制
开发语言·c++·qt·程序人生·个人开发
程序喵大人4 小时前
推荐个C++高性能内存分配器
开发语言·c++·内存分配
zephyr054 小时前
深入浅出C++多态:从虚函数到动态绑定的完全指南
开发语言·c++
码力码力我爱你4 小时前
C++静态变量依赖关系
java·jvm·c++
加勒比之杰克5 小时前
【C++11】Lambda 表达式、可变参数、emplace_back 系列
开发语言·c++·lambda·emplace_back·可变参数模版
Bona Sun5 小时前
单片机手搓掌上游戏机(十一)—esp8266运行gameboy模拟器之硬件连接
c语言·c++·单片机·游戏机
思成不止于此5 小时前
【C++ 数据结构】二叉搜索树:原理、实现与核心操作全解析
开发语言·数据结构·c++·笔记·学习·搜索二叉树·c++40周年