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)
相关推荐
liulun38 分钟前
Windows注册鼠标钩子,获取用户选中的文本
c++·windows·qt
无 证明3 小时前
【C++】类和对象 (第一弹)
开发语言·c++·算法
疾跑哥布林升级版5 小时前
C++---day7
开发语言·c++·算法
程序员老茶5 小时前
C++:函数
开发语言·c++
郭涤生5 小时前
Chapter 7: Compiling C++ Sources with CMake_《Modern CMake for C++》_Notes
c++·笔记·软件构建
fakerth6 小时前
计算机面试八股(自整)
c++·面试
双叶8366 小时前
(51单片机)矩阵按键密码锁表白(C语言代码编撰)(矩阵按键教程)(LCD1602浅教程)
c语言·开发语言·c++·算法·游戏·矩阵·51单片机
海棠蚀omo6 小时前
C++笔记-string(下)
开发语言·c++·笔记
天堂的恶魔9466 小时前
C++ —— 文件操作(流式操作)
c++
dora8 小时前
逼格提起来,使用curl发送网络请求
android·c++