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)
相关推荐
桦06 小时前
【C++复习】:继承
开发语言·c++
鱼难终7 小时前
类和对象(下)
c++
云泽8087 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
邪神与厨二病8 小时前
Problem L. ZZUPC
c++·数学·算法·前缀和
elseif1239 小时前
出题团招人【ETOI_】
c++
第二只羽毛10 小时前
C++ 高并发内存池1
大数据·开发语言·c++·开源
不想看见40410 小时前
C++/Qt 实习岗位深度解析【结合一次研发实习谈感受】
开发语言·c++·qt
王老师青少年编程10 小时前
信奥赛C++提高组csp-s之组合数学专题课:鸽巢原理详解及案例实践
c++·组合数学·信奥赛·抽屉原理·csp-s·提高组·鸽巢原理
njidf10 小时前
C++与Qt图形开发
开发语言·c++·算法
qwehjk200811 小时前
代码动态生成技术
开发语言·c++·算法