C/C++教程

【C++】关于函数重载

本文主要是介绍【C++】关于函数重载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;

//函数重载的条件:
//1. 函数名相同、作用域相同
//2. 函数的参数个数、参数类型、参数类型顺序不同

void func()
{
	cout << "func()" << endl;
}

void func(int a, int b)
{
	cout << "func(int a, int b)" << endl;
}

void func(int a, double b)
{
	cout << "func(int a, double b)" << endl;
}

void func(double b, int a)
{
	cout << "func(double b, int a)" << endl;
}

void test01()
{
	func();
	func(10, 20);
	func(10, 18.18);
	func(18.78, 10);
}


//int func()
//{
//	cout << "func()" << endl;
//}

void tfunc(int a, int b = 10)
{
	cout << "tfunc(int a, int b = 10)" << endl;
}

void tfunc(int a)
{
	cout << "tfunc(int a)" << endl;
}

void rfunc(int& temp)
{
	cout << "rfunc(int& temp)" << endl;
}

void rfunc(const int& temp)
{
	cout << "rfunc(const int& temp)" << endl;
}


void test02()
{
	//函数的返回类型不能作为判断重载的依据
	func();
	//重载要避免二义性
	//tfunc(10);
	//重载的两个引用版本
	int a = 10;
	const int b = a;  //可以通过指针修改
	rfunc(a);
	rfunc(b);
	rfunc(10);

	int* c = (int*)&b;
	*c = 100;
	cout << "b = " << b << endl;
}

int main()
{
	test01();
	test02();

	return 0;
}

这篇关于【C++】关于函数重载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!